views:

628

answers:

5

Hi,

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!

+2  A: 

simple

echo str_replace(array("\r\n", "\r", "\n"), null, $htmlCode);
Ozzy
A: 

It's a simple string substitution.

David Dorward
+1  A: 

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.

Stephen Wrighton
I think you mean .= rather than += .
Chuck
aye.. i blame the 6 years between now and the last time I wrote any php
Stephen Wrighton
A: 

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.

antennen
Feels like an overkill that will affect performance
Alex
In most cases disk I/O is the main bottleneck. I'd do it this way and cache the result.
antennen
+1  A: 

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);
Ben Blank