Topic awaiting preservation: PHP String-Replacement Problem |
|
---|---|
Author | Thread |
Paranoid (IV) Mad Scientist From: Inside THE BOX |
posted 05-31-2005 07:36
Quick one: I'm parsing a string using an array of search/replace items, but I'm tired and can't figure out how to do this one properly. code: $replacements = array( "Company Name, Inc." => "<span class=\"style\">Company Name, Inc.</span>", "Company Name" => "<span class=\"style\">Company Name</span>", "exampletag" => "Example", ); foreach ($replacements as $search => $replace) { $data = ereg_replace("[{]?" . $search . "[}]?", $replace, $data); }
|
Paranoid (IV) Mad Scientist with Finglongers From: Germany |
posted 05-31-2005 09:09
well... the way to do this is code: function compareByLength($strA,$strB) //this might be the wrong way around. replace -1 and 1 with each other. { if (strlen($strA) > strlen($strB)) return 1; elseif (strlen($strA) < strlen($strB)) return -1; else return 0; } $replacements = array( "Company Name, Inc."=>"<span class=\"style\">Company Name, Inc.</span>", "Company Name"=>"<span class=\"style\">Company Name</span>", "exampletag"=>"Example", ); usort($replacements,'compareByLength'); foreach ($replacements as $search => $replace) { $data = preg_replace("/[^>]{1}{?" . $search . "}?", $replace, $data); }
|
Paranoid (IV) Inmate From: Minneapolis |
posted 05-31-2005 23:42
Or you could just change the first pair to: |
Paranoid (IV) Mad Scientist From: Inside THE BOX |
posted 06-03-2005 17:56 |
Bipolar (III) Inmate From: Gainesboro, TN, USA |
posted 06-08-2005 20:24
Ah, I didn't ask the question but it was a good response on both TB and jiblet. |