coder
coder

Reputation: 37

string replace exact word in php

php

$aaa="";
echo $nn="ab bc cd cde ab aa";
echo "<br>";
echo $n=preg_replace('/cd|ab/', '$aaa', $nn);
echo "<br>";
echo $no=preg_replace('/[a-z]/', '$bbb', $n);
echo "<br><br>";

The output I was expecting is "$aaa $bbb $aaa $bbb $bbb $bbb".That is when the pattern 'cd' or 'ab' alone is matched it should change to '$aaa' and those unmatched to '$bbb'.

Upvotes: 1

Views: 554

Answers (1)

Jason Spicer
Jason Spicer

Reputation: 239

$aaa="";
echo $nn="ab bc cd cde ab aa";
echo "<br>";
echo $n=preg_replace('/\b(cd|ab)\b/', '$aaa', $nn);
echo "<br>";
echo $no=preg_replace('/((?<= )[a-z]+)\b/', '$bbb', $n);
echo "<br><br>";

The first replace matches within: cd or ab within word boundaries (i.e. spaces or start/end of string)

The second replace matches (a-z) 1 or more times, preceded by a space (since $ is also a word boundary). The only downside is that this won't match cde if cde were to be the start of the string.

Upvotes: 1

Related Questions