Multiple Word Search and RegEx Matching

I created a function that selects individual words inside a string. It looks like this:

function highlight($input, $keywords) { preg_match_all('~[\w\'"-]+~', $keywords, $match); if(!$match) { return $input; } $result = '~\\b(' . implode('|', $match[0]) . ')\\b~i'; return preg_replace($result, '<strong>$0</strong>', $input); } 

I need a function to work with an array of different words that support a space in the search.

Example:

$search = array("this needs", "here", "can high-light the text");

$string = "This needs to be in here so that the search variable can high-light the text";

echo highlight($string, $search);

Here is what I have been fixing so far to work as I need it:

 function highlight($input, $keywords) { foreach($keywords as $keyword) { preg_match_all('~[\w\'"-]+~', $keyword, $match); if(!$match) { return $input; } $result = '~\\b(' . implode('|', $match[0]) . ')\\b~i'; $output .= preg_replace($result, '<strong>$0</strong>', $keyword); } return $output; } 

Obviously, this does not work, and I'm not sure how to make it work (regular expression is not my forte).

Another issue that could be a problem, how will a function deal with multiple matches? For example, $search = array("in here", "here so"); the result will be something like:

This needs to be <strong>in <strong>here</strong> so</strong> that the search variable can high-light the text

But it should be:

This needs to be <strong>in here so</strong> that the search variable can high-light the text

+4
source share
1 answer

Description

Can you take your array of terms and join them with a regular expression or expression | and then nest them in a string. \b helps you not capture snippets of words.

\b(this needs|here|can high-light the text)\b

enter image description here

Then run this as a replacement using capture group \1 ?

Example

I am not very familiar with Python, but in PHP I would do something like this:

 <?php $sourcestring="This needs to be in here so that the search variable can high-light the text"; echo preg_replace('/\b(this needs|here|can high-light the text)\b/i','<strong>\1</strong>',$sourcestring); ?> $sourcestring after replacement: <strong>This needs</strong> to be in <strong>here</strong> so that the search variable <strong>can high-light the text</strong> 
+3
source

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


All Articles