RE: [PHP] Replacing 2 strings

From: Date: Tue, 31 May 2005 02:08:43 +0000
Subject: RE: [PHP] Replacing 2 strings
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-216017@lists.php.net to get a copy of this message
> <?php // this will produce JIM JONES > > function replace($string, $search) > { > $string = strstr($string, $search) > $string = preg_replace("/(<|\^|>)/", "",$string); > $string = str_replace("_", " ", $string); > return $string; > > } > > $text = 'My name is <^JIM_JONES> and I like ice cream'; > $search_string = '<^JIM_JONES>'; > echo replace($text, $search_string); > > ?> This is a pretty good solution, however for the sake of paranoia about potentially removing characters that Will may not want targeted by the function (i.e., what if "<", ">", "^" or "_" legitimately appear later in the string and are accidentally removed?), I'd do something like the following: <? function replace($string){ preg_match("/^<\^([a-zA-Z]+?)_([a-zA-Z]+?)>/", $string, $matcharr); $string = str_replace($matcharr[0], $matcharr[1] . " " .$matcharr[2] . ":", $string); return $string; } $string = "<^JIM_JONES> Leicester, 1720. Oxford, 1800 CONFIRMED: meeting at 19.10"; echo replace($string); ?> One of the small benefits of this solution is that Will doesn't need to know what is contained in the target substring beforehand. Regards, Murray

« previous php.general (#216017) next »