Maximilian Travis
Maximilian Travis

Reputation: 331

How can i replace words in a string using an array in php?

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.

Upvotes: 1

Views: 3697

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 79014

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);

Upvotes: 4

ameenulla0007
ameenulla0007

Reputation: 2683

$colors = array('red' => 'i am the color red', 'blue' => 'hi Im blue');
$string = "red, blue, red, and lots of blue";
foreach($colors as $key => $value) {
    $string = str_replace($key, $value, $string);
}
echo $string;

use the above code to get your expected result.

Upvotes: 1

MichaelWClark
MichaelWClark

Reputation: 390

http://php.net/manual/en/function.str-replace.php

echo str-replace($key, $value, $string);

Upvotes: 0

Related Questions