Reputation: 9521
I am trying to replace occurances of whole words in a string. There are similar questions here at SO like this and this.
Answers to all these questions recommend using regex like this:
$needle = "a";
$haystack = "oh my dear a";
$haystack = preg_replace("/$needle\b/", 'God', $haystack);
echo $haystack;
This works good for whole words - echoes oh my dear God
But if I replace a
with a.
in both needle and haystack, i;e
$needle = "a.";
$haystack = "oh my dear a.";
the output becomes oh my deGod a.
because .
gets evaluated as regex.
I would want a.
to be replaced by God
with or without regex.
Upvotes: 1
Views: 570
Reputation: 70732
\b
refers only to word boundaries in an ASCII perception. Also .
is a character of special meaning in regular expression — meaning "match any single character (except newline)"
If the "needle" may contain special characters, use preg_quote()
and create DIY boundaries.
preg_quote()
takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.
$str = preg_replace("~(?<=^| )" . preg_quote($needle, "~") . "(?= |$)~", 'God', $str);
Upvotes: 1
Reputation: 41
Maybe this will give you an inspiration...
$haystack="oh my dear a." ;
$needle="a" ;
$hout=$haystack ;
$hout=~ s/\b$needle\b\./God/g ;
print "$haystack $needle $hout\n";
...produces this output...
oh my dear a. a oh my dear God
This works in perl. Sorry, my php is way rusty.
Upvotes: 1