Preg_replace Cyrillic word or phrase - not both

I am writing a PHP function that should convert certain keywords into links. It uses cyrillic words in UTF-8. So I came up with this:

function keywords($text){ $keywords = Db::get('keywords'); //array with words and corresponding links foreach ($keywords as $value){ $keyword = $value['keyword']; $link = $value['link']; $text = preg_replace('/(?<!\pL)('.$keyword.')(?!\pL)/iu', '<a href='.$link.' class="linked">$1</a>', $text); } return $text; } 

So far it works like a charm, but now I want to replace phrases with links - phrases that may contain other keywords. For example, I want the word โ€œcarโ€ to be associated with one place, and โ€œblue carโ€ to be associated with another.

Any ideas?

+4
source share
1 answer

As written in the commentary, I am posting this as an answer, hoping it will be useful to you.

You could try to replace the keyword in the text first, using a placeholder, and then, when all the text has been analyzed, you can replace these placeholders with real words.

For example, take the phrase:

 "I have a car, a blue car." 

We already ordered a list of keywords from longer to smaller, so we check the "blue car"; We find this in the text, so we place a placeholder and get:

 "I have a car, a [[1]]." 

The second keyword on the list is โ€œcarโ€; after substitution in the text we get:

 "I have a [[2]], a [[1]]." 

Finally, when all the keywords have been replaced, you only need to replace the placeholders in their order, using preg_replace in your function, and get the text with links.

+1
source

Source: https://habr.com/ru/post/1483137/


All Articles