Issue
I am trying to search a string and replace all instances of a certain string with another other string every time the first string appears.
My goal is to avoid using many preg-replace statements and to make an array which is easily editable and maintainable, containing keys that are identical to the words i'm looking to replace and values containing the replacements.
So far I've got something like this:
$colors = array('red' => 'i am the color red', 'blue' => 'hi I am blue',);
$string = "red, blue, red, and lots of blue";
foreach($colors as $key => $value) {
preg_replace($key, $value, $string);
echo $string;
}
This is not yet working.
Solution
You are doing straight string replacement (no regular expressions) so use:
$string = str_replace(array_keys($colors), $colors, $string);
No loop needed, str_replace()
takes arrays.
FYI: In your code, aside from the parse error, you aren't assigning the return of the preg_replace()
back to a string to be used and regex using a specific a pattern with delimiters and special syntax. You need word boundaries \b
as well to keep from replacing the red
in redefine
and undelivered
etc.:
$string = preg_replace("/\b$key\b/", $value, $string);
Answered By - AbraCadaver Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.