繁体   English   中英

PHP正则表达式格式文本

[英]PHP regular expression format text

我需要有关php5正则表达式功能的帮助。 我需要一个函数,该函数接受参数文本,正则表达式,字符串之前,之后。

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

这个例子可能是我需要的最好的解释。

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

我需要退货

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

一个例子只是为了说明问题,它不会是html元素。

谢谢

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

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

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

在线演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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