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]?

Recommended Answers

All 4 Replies

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

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

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);
}

Thx, big thx!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.