简体   繁体   中英

PHP regular expression format text

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

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

print preg_replace("@".$regex."@", $before."$1".$after, $text);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM