繁体   English   中英

在 PHP 中使用正则表达式删除文本

[英]Removing text with regular expression in PHP

变量字符串包含的行为

重要 1
一些单词......
重要 34
一些单词......
重要 99
一些单词......

目标是删除包含important一词的行,忽略带有符号$的大小写。 重要一词还包含一个数字。 此行也可能在一些 HTML 代码如<b>important 1</b><br />

到目前为止我的代码:

<?php
$patterns = '/(important)\s{1,2}\d{1,2}\/';
preg_replace($patterns, '$', $string);
?>

所需的 output:

$ some words ......  
$ some words ......  
$ some words ......

关于模式的一些注意事项

  • important 周围不需要捕获组,并添加一个单词边界\b以防止匹配unimportant
  • \s也可以匹配换行符
  • 如果要匹配该行的 rest,则不必使用\d{1,2}中的量词作为. 也可以匹配一个数字
  • 要在匹配行后匹配换行符,可以使用\R在问题中得到想要的结果

你可能会使用

^.*\bimportant\h+\d.*\R*

解释

  • ^字符串开始
  • .*匹配除换行符之外的任何字符
  • \bimportant\h+一个单词边界,匹配important和 1+ 水平空白字符
  • \d.*至少匹配一个数字和该行的 rest
  • \R*匹配一个可选的换行序列

正则表达式演示| Php演示

示例代码

$pattern = '/^.*\bimportant\h+\d.*\R*/mi';
$string = 'important 1
some words ......
IMPORTANT 34
some words ......
important 99
some words ......';

$result = preg_replace($pattern, '', $string);

echo $result;

Output

some words ......
some words ......
some words ......

如果您只想匹配整行并使用$断言字符串的结尾,您可以使用:

^.*\bimportant\h+\d.*$

正则表达式演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM