InsaneSVK
InsaneSVK

Reputation: 206

preg_replace with two similar words

I have a problem with two very similar expressions in Slovak language. I'm trying to replace the expression for a html link, this is my example code below. I have about 90 words in the array.

// mysql query above.
for($i=1;$i<=$datas[1];$i++) {
  $regex[] = '/('.htmlentities($rows['title'], ENT_QUOTES, 'UTF-8').')/i';
  $wrl[] = '<a href="'.URL.'link/'.urlencode($rows['alias']).'" class="underscored">'.strtolower($rows['title']).'</a>';
}
$content = preg_replace($regex, $wrl, $content);

But I have a problem with very similar words; (nenasytene mastne kyseliny, nasytene mastne kyseliny). preg_replace removes the ne from the longer word, which results in the word being linked to a wrong article.

Upvotes: 0

Views: 154

Answers (2)

Jon
Jon

Reputation: 13002

Try modifying your regular expression to specify a word boundary \b before and after the phrase you want to replace with a link:

$regex[] = '/\b('.htmlentities($rows['title'], ENT_QUOTES, 'UTF-8').')\b/i';

Upvotes: 1

hsz
hsz

Reputation: 152294

You can prepend and append your regex with \W:

$regex[] = '/\W('.htmlentities($rows['title'], ENT_QUOTES, 'UTF-8').')\W/i';

Upvotes: 0

Related Questions