请考虑以下几点:
$string = "Hello, there! Welcome to <>?@#$!& our site<!END!>";我试图删除除字母、数字、空格和“特殊标签”<!END!>以外的所有内容
使用preg_replace,我可以这样写:
$string = preg_replace("/[^A-Za-z0-9 ]/", "", $string);移除除字母(大写和小写)、数字和空格以外的所有内容。现在,如果我也想忽略<!END!>标记,理论上我可以这样写:
$string = preg_replace("/[^A-Za-z0-9 <!END!>]/", "", $string);但是,这并不会特别忽略标记<!END!>,而是忽略它包含的任何字符。所以它将保存每一个<,>,和!在$string中。
结果:
"Hello there! Welcome to <>! our site<!END!>"但我想要:
"Hello there Welcome to  our site<!END!>"根据我的研究,应该可以使用\b标记在preg_replace中包含一个要忽略的特定单词,但是"/[^A-Za-z0-9 \b<!END!>\b]/"给了我与上面相同的结果。
我做错了什么吗?
现场演示:http://sandbox.onlinephpfunctions.com/code/219dc36ab8aa7dfa16e8e623f5f4ba7f4b4b930d
发布于 2018-06-29 13:25:10
您可以使用(*SKIP)(*F)解决方案:
这将符合:
<!END!>(*SKIP)(FAIL)匹配<!END!>,然后跳过该匹配|或[^A-Za-z0-9 ]匹配不使用字符类中指定的内容例如:
$string = "Hello, there! Welcome to <>?@#$!& our site<!END!>";
$string = preg_replace("/<!END!>(*SKIP)(FAIL)|[^A-Za-z0-9 ]/", "", $string);
echo $string;这将导致:
欢迎来到我们的site
https://stackoverflow.com/questions/51102482
复制相似问题