Re: str_replace() problems actually *_replace() problems to be

From: Date: Mon, 16 Jun 2003 21:27:33 +0000
Subject: Re: str_replace() problems actually *_replace() problems to be
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-151734@lists.php.net to get a copy of this message
Thanks, I was so hung up on the regex that I failed to spot the (obscenely) obvious through my tunnel vision. Sometimes a fresh pair of eyes makes all the difference. Anyhow, the understatement of the day award goes to Lars for "There's only one thing you didn't try..." ;-) Thanks again, Tom Lars Torben Wilson wrote:
On Mon, 2003-06-16 at 11:49, Thomas Bolioli wrote:
I am a perl/java/c++ programmer who is doing something in php and have run accross something I am stumped with. I am trying to replace carriage returns with <br> or <p> tags (p's in groups of two and br's for any unmatched cr's). I have tried all of the *_replace() functions including string_*, ereg_* and preg_*. None have worked the way they seem to should. Note, I am a perl programmer and preg_replace() did not work while a test perl script did. I have tried multiple forms of patterns from "\r\n" to "\n" to "\r" to "/\r?\n/ei" (in the *reg_* functions). I even took code verbatim from examples in the docs to no avail. I have included the entire block of code (and mysql_dump output) since there is something I have apparently not done right and it may not be in the pattern matches. Thanks in advance, Tom
Hi Tom, There's only one thing you didn't try...see below:
*The offending code:* }elseif($_REQUEST['add']){ $desc = $_REQUEST['description']; str_replace("\r\n\r\n", "<p>", $desc); str_replace("\r\n", "<br>", $desc);
You need to assign the result of the replacement to something before you can use it; arguments are not modified in place. So something like this: $desc = str_replace("\r\n\r\n", "<p>", $desc); $desc = str_replace("\r\n", "<br>", $desc); This change shouild be all you need. However, if you want to be able to accept input from other than windows users, you can do the whole thing with strtr(). I haven't tested with preg_replace(), but I suspect that using regexps for this would be overkill. $trans = array("\n\n" => '<p>',
                 "\n" => '<br />',
                 "\r\r" => '<p>',
                 "\r" => '<br />',
                 "\r\n\r\n" => '<p>',
                 "\r\n" => '<br />');
$desc = strtr($desc, $trans); Hope this helps, Torben


« previous php.general (#151734) next »