php-source-func-preg_replace_callback
2015-07-31 00:00
781 查看
概述:preg_replace_callback函数的用法
首先大概基本测试一下:
文档介绍:自定义函数的参数是preg_match函数匹配的结果数组;函数返回值是替换之后的结果。
函数执行结果:
看到返回值结果,好难受….
回调函数返回了一个return值,用来替代查询的结果。函数执行的结果如下:
函数预期还是很不错的,结合了preg_match和preg_replace两个函数的功能,到底有没有节约代码就不知道了。
测试一下替换数组的实现:
执行结果:
下次就可以使用这个函数了.
首先大概基本测试一下:
<?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>" }
下次就可以使用这个函数了.
相关文章推荐
- PHP8新特性之match表达式
- cmd replace 文件替换使用说明
- ASP中让Replace替换不区分大小写的方法
- SQL中函数 replace 的参数1的数据类型ntext无效的解决方法
- asp提示无效使用 Null: Replace
- js正则表达exec与match的区别说明
- js replace 与replaceall实例用法详解
- Jquery replace 字符替换实现代码
- js中replace的用法总结
- mysql数据库replace、regexp的用法
- javascript replace()方法的简单分析
- MySQL Replace INTO的使用
- MySQL中REPLACE INTO和INSERT INTO的区别分析
- mySQL中replace的用法
- JavaScript中使用replace结合正则实现replaceAll的效果
- MySQL replace函数替换字符串语句的用法
- javascript replace方法与正则表达式
- Document.location.href和.replace的区别示例介绍
- javascript笔记 String类replace函数的一些事
- js中关于String对象的replace使用详解