MalcolmInTheCenter
MalcolmInTheCenter

Reputation: 1605

PHP Regex: How do I replace all occurrences of a word starting with a colon?

I want to replace all the :first_name occurrences in my $body variable with $first_name but i'm stuck with the regex part. The regex isn't working. When I echo the body the original string gets printed. What's the correct regex?

$first_name = "Joe";
$body = "Hi :first_name. Have a nice day :first_name!";
$regex = "/\b:first_name\b/";
$body = preg_replace($regex, $first_name, $body);
echo $body;

Upvotes: 1

Views: 344

Answers (2)

Srdjan M.
Srdjan M.

Reputation: 3405

Regex: :\w+ or :first_name

$first_name = "Joe";
$text = "Hi :first_name. Have a nice day :first_name!";

$text = preg_replace('/:(\w+)/', $first_name, $text);

print_r($text);

Output:

Hi Joe. Have a nice day Joe!

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

Since you asked in the comments, this is more extensible and should be easier. Use str_replace and an array:

$array[':first_name'] = "Joe";
$array[':last_name'] = "Smith";

$body = str_replace(array_keys($array), $array, $body);

Another alternative with strtr:

$body = strtr($body, $array);

Upvotes: 5

Related Questions