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

Sam*_*ala 4 php regex

这是如何做到的,有几行:

// $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"
Run Code Online (Sandbox Code Playgroud)

我的问题集中在将两个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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Sup*_*Dud 7

$str = preg_replace(
    $patterns = array('/[\x00-\x09\x0B-\x1F\x7F]|^ +| +$/', '/\x0A| +/'),
    $replace  = array('',                                   ' '), 
    $str
);
Run Code Online (Sandbox Code Playgroud)

preg_replace,它支持彼此之后的多次替换.

  • @hakre我喜欢你编辑的方式.只是好奇,这样做你甚至需要$ patterns和$ replace变量?你能让这些数组匿名吗? (2认同)