gpt4 book ai didi

php - preg_replace 能否一次进行多个搜索和替换操作?

转载 作者:可可西里 更新时间:2023-10-31 22:14:13 24 4
gpt4 key购买 nike

这是如何完成的,分几行:

// $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() 来完成完全相同的工作。

这可能吗?如果是的话应该怎么做?


该行为有许多不同的用途,我所追求的一种用途是将正则表达式定义为常量或变量,并在类函数中使用它来清理和验证用户输入。

此类的简化示例:

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 能否一次进行多个搜索和替换操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10192646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com