preg_replace_callback 使用回调执行正则表达式搜索和替换
时间:2023-3-1 21:07 作者:wen 分类: PHP
/*
使输入字符串中的所有 HTML 标记变成小写。
@param str $html html代码
@return str 返回html内容
*/
function htmltolower($html)
{
return preg_replace_callback("/(<\/?)(\w+)([^>]*>)/", function ($matches) {
return $matches[1] . strtolower($matches[2]) . $matches[3];
}, $html);
}
也可以写成这样
<?php
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// 回调函数
function next_year($matches)
{
return $matches[1].($matches[2]+1);
}
echo preg_replace_callback("|(\d{2}/\d{2}/)(\d{4})|", "next_year", $text);