加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – preg_replace可以一次性进行多次搜索和替换操作吗?

发布时间:2020-12-13 17:41:16 所属栏目:PHP教程 来源:网络整理
导读:这是如何做到的,有几行: // $str represents string that needs cleaning:$str = " String with linenbreak and too much spaces ";// Clean string with preg_replace():$str = preg_replace('/[x00-x09x0B-x1Fx7F]|^ +| +$/','',$str);$str = preg_
这是如何做到的,有几行:

// $str represents string that needs cleaning:
$str = " String with   linenbreak and too  much spaces   ";
// Clean string with preg_replace():
$str = preg_replace('/[x00-x09x0B-x1Fx7F]|^ +| +$/','',$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-x1Fx7F]/','TRIM_STRIP_CC' => array('/[x00-x1Fx7F]/','/ +/')
    );
    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;
    }
}

这样,验证方法(regexp)可以根据需要随输入数据而变化.

解决方法

$str = preg_replace(
    $patterns = array('/[x00-x09x0B-x1Fx7F]|^ +| +$/','/x0A| +/'),$replace  = array('',' '),$str
);

preg_replace,它支持多个替换后.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读