脚本宝典收集整理的这篇文章主要介绍了php – preg_replace可以一次性进行多次搜索和替换操作吗?,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
// $str rePResents string that needs cleaning: $str = " String wITh line\nbreak and too much spaces "; // Clean string with preg_replace(): $str = preg_replace('/[\x00-\x09\x0B-\x1F\x7F]|^ +| +$/','',$str); $str = preg_replace('/\x0A| +/',' ',$str); echo $str; // Output: "String with line break and too much spaces"
我的问题集中在将两个preg_replace()行组合成一个preg_replace(),它完成相同的工作.
这是可能的,如果它应该如何做?
这种行为有许多不同的用途,我所追求的是将regexp定义为常量或变量,并在类函数中使用它来清理和验证用户输入.
这类的简化示例:
class cleaner{ protected $defined_methods = array( 'TRIM' => '/ +/','STRIP_CC' => '/[\x00-\x1F\x7F]/','TRIM_STRIP_CC' => array('/[\x00-\x1F\x7F]/','/ +/') ); protected $defined_results = array( 'TRIM' => ' ','STRIP_CC' => '','TRIM_STRIP_CC' => array('',' ') ); function clean(array $input,array $methods){ foreach ($input as $key => $data){ $input[$key] = preg_replace($defined_methods[$methods[$key]],$defined_results[$methods[$key]],$data); } return $input; } }
$str = preg_replace( $patterns = array('/[\x00-\x09\x0B-\x1F\x7F]|^ +| +$/','/\x0A| +/'),$replace = array('',' '),$str );
见preg_replace
,它支持多个替换后.
以上是脚本宝典为你收集整理的php – preg_replace可以一次性进行多次搜索和替换操作吗?全部内容,希望文章能够帮你解决php – preg_replace可以一次性进行多次搜索和替换操作吗?所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。