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

From: Date: Mon, 16 Jun 2003 21:08:35 +0000
Subject: Re: str_replace() problems actually *_replace() problems to be more accurate
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-151726@lists.php.net to get a copy of this message
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 -- Torben Wilson <torben@php.net> +1.604.709.0506 http://www.thebuttlesschaps.com http://www.inflatableeye.com http://www.hybrid17.com http://www.themainonmain.com -----==== Boycott Starbucks! http://www.haidabuckscafe.com ====-----

« previous php.general (#151726) next »