I'm using a javascript function that receives some html code that was included using php. It is not html in a php string but an html file with .php extension.
As the html code is sent as a parameter to the js function it can't contain carriage returns. The problem is that writing big blocks of html in a single line is terrible, I would like to have a function only to erase the carriage returns before sending the content.
Is there a source for such a function?
Thanks!
I'm using a javascript function that receives some html code that was included using php. It is not html in a php string but an html file with .php extension.
As the html code is sent as a parameter to the js function it can't contain carriage returns. The problem is that writing big blocks of html in a single line is terrible, I would like to have a function only to erase the carriage returns before sending the content.
Is there a source for such a function?
Thanks!
Share Improve this question edited Jun 3, 2009 at 16:25 Lucia asked Jun 3, 2009 at 15:58 LuciaLucia 4,7876 gold badges47 silver badges58 bronze badges5 Answers
Reset to default 6simple
echo str_replace(array("\r\n", "\r", "\n"), null, $htmlCode);
When you say "in a PHP file", I assume you mean you're include()
ing a file that looks something like this:
<html>
<head><title>Foo</title></head>
<body>
<?php do_stuff(); ?>
</body>
</html>
If that's the case, what you're looking for is called Output Control, which allows you to either prevent data from being sent until you're ready or capture it to a string for additional processing. To strip carriage returns from an included file, you can do this:
<?php
ob_start(); // start buffering output
include("foo.php"); // include your file
$foo = ob_get_contents(); // get a copy of the buffer's contents
ob_clean_end(); // discard the buffer and turn off buffering
echo str_replace("\r", "", $foo); // print output w/o carriage returns
If you want to remove newlines as well, change that last line to:
echo str_replace(array("\n", "\r"), "", $foo);
by "building it in PHP" I assume you mean that you're building a string which contains the relevant HTML.
If that's the case, then it's a simple matter of not having the carriage returns as a part of your string.
i.e., don't do this:
foo = " this is my string
and I have it on two lines";
but rather do this
foo = "" .
" this is my string" .
" and it's on one line ";
Sure, you could use a string.replace function, but building via concats means that you get to skip that step.
It's a simple string substitution.
Consider using a XML writer for this, if that's what your javascript parses. That way the result will always be valid, and the code should get cleaner.