Question

I have the string

'OR "law studies"~2 AND here also NOT uni*  "south West" word NOT this *eng'

I want to use preg_replace_callback() to process all the process all words that are between (AND|OR|NOT) I'm struggling with the regex pattern. Can you please suggest a regex pattern that will match that criteria I want the the final result to be

OR
"law studies"~2
AND
here also
NOT
uni* "south West" word
NOT
this *eng

OR "law studies"~2 AND here also NOT uni* "south West" word NOT this *eng I've tried everything with no avail

Thank you in advance

Was it helpful?

Solution

There are a couple of ways you can address this problem. First, I will address it using preg_replace_callback, since that's specifically what you are asking for in your question:

$string = 'OR "law studies"~2 AND here also NOT uni*  "south West" word NOT this *eng';

$string = preg_replace_callback('~(.*?)(?:OR|AND|NOT|$)~', 'callback_function', $string);

print $string;

function callback_function ($m) {

    $return_string = preg_replace('/e/', '<b><font color=red>e</font></b>', $m[1]);

    return $return_string;

}

This will highlight all of the "e"s in your string with bold and red.

There is also a similar function that you can use accomplish the same thing: preg_split. What this does is split a string into an array, based on a regular expression. Here's some code to demonstrate:

$string = 'OR "law studies"~2 AND here also NOT uni*  "south West" word NOT this *eng';

$keywords = preg_split("/(OR|AND|NOT)/", $string, -1, PREG_SPLIT_NO_EMPTY); // NO EMPTY LINES

$keywords will contain the following:

Array
(
    [0] =>  "law studies"~2 
    [1] =>  here also 
    [2] =>  uni*  "south West" word 
    [3] =>  this *eng
)

So then you can loop through each item of the array and do a replacement in the string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top