php搜索十可搜索一次,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;

}

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值