您的位置:首页 > 编程语言 > PHP开发

php-source-func-preg_replace_callback

2015-07-31 00:00 781 查看
概述:preg_replace_callback函数的用法

首先大概基本测试一下:

<?php
$str = "<root><content><a href='http://www.sina.com.cn'>why not</a></content><root>";
$regx = '/<content>(.*)<\/content>/';
$rep_result = preg_replace_callback(
$regx,
function($match){
var_dump($match);
},
$str
);
echo $rep_result;
?>


文档介绍:自定义函数的参数是preg_match函数匹配的结果数组;函数返回值是替换之后的结果。

函数执行结果:

array(2) {
[0] =>
string(63) "<content><a href='http://www.sina.com.cn'>why not</a></content>"
[1] =>
string(44) "<a href='http://www.sina.com.cn'>why not</a>"
}
<root><root>


看到返回值结果,好难受….

<?php
$str = "<root><content><a href='http://www.sina.com.cn'>why not</a></content><root>";
$regx = '/<content>(.*)<\/content>/';
$rep_result = preg_replace_callback(
$regx,
function($match){
return $match[1];
},
$str
);
echo $rep_result;
?>


回调函数返回了一个return值,用来替代查询的结果。函数执行的结果如下:

<root><a href='http://www.sina.com.cn'>why not</a><root>


函数预期还是很不错的,结合了preg_match和preg_replace两个函数的功能,到底有没有节约代码就不知道了。

测试一下替换数组的实现:

<?php
$str = array(
'one' => "<root><content><a href='http://www.sina.com.cn'>who am i</a></content><root>",
'two' => "<root><content><a href='http://www.sina.com.cn'>which is</a></content><root>");
$regx = '/<content>(.*)<\/content>/';
$rep_result = preg_replace_callback(
$regx,
function($match){
return $match[1];
},
$str
);
var_dump($rep_result);
?>


执行结果:

array(2) {
'one' =>
string(57) "<root><a href='http://www.sina.com.cn'>who am i</a><root>"
'two' =>
string(57) "<root><a href='http://www.sina.com.cn'>which is</a><root>"
}


下次就可以使用这个函数了.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  preg replace match