合并两个正则表达式

时间:2013-08-02 06:38:58

标签: php regex

function regexp($text){
   $text = preg_replace('#!test=#', '', $text);
   $text = preg_replace('#@test=#', '', $text);
   return $text;
}

我如何合并这个正则表达式?他们只有不同!和@。在我的例子中是错误,这不起作用。我想简单地说:

$a = 'asdf!test=wer';
$b = '232@test=dsf';

更改为:

$a = 'asdfwer';
$b = '232dsf';

with regexp。

2 个答案:

答案 0 :(得分:4)

这样的东西应该匹配:#(!|@)test=#。如果您有更多符号(!@除外,请将其替换为以下内容:#[!@]test=#(由@DCoder建议)将产生更清晰的正则表达式。

基本上,正则表达式语言中的管道(|)表示OR。基本上,我说匹配字符串test=,如果它带有!@符号的前缀。

答案 1 :(得分:0)

尝试使用带有替换数组的正则表达式数组preg_replace,如

$text = preg_replace(array('#!test=#' , '#@test=#'),array('' , ''), $text);