我需要知道是否有任何方法将两个正则表达式合并为单个regexp。最近,我不得不制作以下php代码,但我觉得有一种简化的方法来实现这一点,而无需使用多个preg_replace标签。我要做的是剥离 & ©
等。并删除所有多个空格
$textinput = 'this is a test input '' """""" """" @#$$%&*)_+!@#$%^&*) 123 456';
$var = preg_replace("/&#?[a-z0-9]{2,8};/i",'',$textinput)
$string = preg_replace('/'s+/', ' ', $var);
输出this is a test input ' """""""""" @#$$%&*)_+!@#$%^&*) 123 456
我知道html_entity_decode
函数在php中剥离特殊字符,这只是一个例子!我怎么能把两个regexp合并成一个?
谢谢!
这将在一个有效的步骤中完成两次替换(而不会丢失空白字符):
$replaced = preg_replace('~(?:&#?[a-z0-9]{2,8};)+|'s'K's+~', '', $yourstring);
在演示中,看看所有额外的字符是如何定位的。
- 左侧的
|
,(?:&#?[a-z0-9]{2,8};)+
的目标群,如
,不是一次一个,而是几个在一起,如果他们接触。 - 在右侧,
's
匹配一个空格,然后'K
告诉引擎将其从匹配中删除(它不会被替换),然后's+
匹配 后面的任何空白字符 - 用空字符串替换。
$var = preg_replace_callback('/&#?[a-z0-9]{2,8};|'s+/i', function($match) {
return $match[0][0] === '&' ? '' : ' ';
}, $textinput);
您可以使用逻辑或运算符来组合两个正则表达式,
(?:&#?[a-z0-9]{2,8};)+|(?<='s)'s+
你的代码应该是,
<?php
$mystring = 'this is a test input '' """""" """" @#$$%&*)_+!@#$%^&*) 123 456';
$pattern = "~(?:&#?[a-z0-9]{2,8};)+|(?<='s)'s+~";
$replacement = "";
echo preg_replace($pattern, $replacement, $mystring);
?>
或
<?php
$mystring = 'this is a test input '' """""" """" @#$$%&*)_+!@#$%^&*) 123 456';
$pattern = "~&#?[a-z0-9]{2,8};|(?<='s)'s+~";
$replacement = "";
echo preg_replace($pattern, $replacement, $mystring);
?>
输出:this is a test input ' """""" """" @#$$%&*)_+!@#$%^&*) 123 456