0

I need help with php5 regex function. I need function which takes arguments text, Regex, string before, after.

function Highlight($text, $regex, $before, $after)

example is probably the best explanation of what I need.

$text="I have apple and banana."
$regex="(apple|banana)"
$before="<b>"
$after="</b>"

and I need return

"I have <b>apple</b> and <b>banana<b>."

an example is only to illustrate the problem and it will not be an html elements.

thank you

3
  • Have you tried preg_replace_callback()? Commented Mar 8, 2014 at 10:59
  • Please also include any code that you have tried and why it didn't work. Commented Mar 8, 2014 at 10:59
  • Are those strings guaranteed not to be in a HTML-attribute in your text-to-highlight? If so: a simple preg_replace should do it. If however you cannot know for certain, going for a DOM parser & inspect the text nodes individually is less prone to errors. Commented Mar 8, 2014 at 11:01

2 Answers 2

3
$text="I have apple and banana.";
$regex="(apple|banana)";
$before="<b>";
$after="</b>";

print preg_replace("@".$regex."@", $before."$1".$after, $text);
Sign up to request clarification or add additional context in comments.

Comments

1

Use preg_replace_callback():

function Highlight($text, $regex, $before, $after) {
    $pattern = '/'. $regex .'/';
    return preg_replace_callback($pattern, 
        function ($m) use ($before,$after) {
            return $before.$m[0].$after;
        }
    , $text);
}

Online demo

1 Comment

@ComFreek: Absolutely right. I hadn't tested the code before posting the answer. But these errors have been fixed. Thanks for catching that for me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.