0

I have e.g. example:

$some_text='some example text [title=some_title]some title[/title] next text';

and I want make function, which will search for the word.

I make function:

function text_check($text,$search_word)
{
    $text = preg_replace('/'.$search_word.'/i','<span style="color: red;">'.$search_word.'</span>',$text);
    return $text;
}

 $search='title';

echo text_check($some_text,$search);

How to construct a function of instruction which will steer clear of the bbcode [title=some_title]?

2
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by piotrekw
1

Apparently you need to use negative assetions, as described here

So, for your case, where you don't want the text matched if it's between square brackets, you would use:

(?!\[)(\bsome title\b)(?!\])

function highlight($string, $term)
{
    return preg_replace("/(?!\[)(\b{$term}\b)(?!\])/i", '<span style="color:#f00;">\${1}</span>', $string);
}

R

0

Thx!
I almost did - but select the first search word in brackets:

function highlight($string, $term)
{
    return preg_replace("/(?!\[)(\b{$term}\b)(?!\])/i", "<span style=\"color:#f00;\">\${1}</span>", $string);
}

$some_text='some example text [title=some_title]some title[/title] next text';
echo highlight($some_text,'title'); 

The result is:

some example text [<span style="color:#f00;">title</span>=some_title]some <span style="color:#f00;">title</span>[/title] next text
1

I missed a character when modifying the regex. Try:

function highlight($string, $term)
{
    return preg_replace("/(?<!\[)(\b{$term}\b)(?!\])/i", '<span style="color:#f00;">\\1</span>', $string);
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.