Marverick M.
Marverick M.

Reputation: 124

replace the exact word without replacing the not exact word with str_replace

i have this problem replacing a word but it replace other

$dbword = 'test text lorem ipsum ext';
$var1 = str_replace($dbword, 'ext', $var);
$var1 = str_replace($$dbword, 'text', $var1);

i want to replace the text without arranging the line, because the ext and text words are from the database and sorting the query is not the best way for me.

how can I replace the words without changing the look a like word? please help thanks in advance

Upvotes: 1

Views: 121

Answers (1)

a4w
a4w

Reputation: 577

you should use preg_replace like :

$dbword = 'test text lorem ipsum ext';
$rplc = 'replaced';
$pattern = '/\bext\b/u';
$ret = preg_replace($pattern,$rplc,$dbword);//test text lorem ipsum replaced
$pattern2 = '/\btext\b/u';
$ret2 = preg_replace($pattern2,$rplc,$dbword);//test replaced lorem ipsum ext

Upvotes: 2

Related Questions