这是如何做到的,有几行:
// $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)可以根据需要随输入数据而变化.