使用正则表达式在特定事件后替换单行中的文本

时间:2014-05-03 01:53:43

标签: php regex

我已经在这个网站上搜索了一个问题的解决方案但是没有找到使用正则表达式完成此任务的方法(或者可能只是缩短了使用更少内存的东西)。   我试图解析一个字符串,其中特定模式(&模式本身)之后的文本将从同一行中删除。模式之前的文本以及不包含搜索模式的任何行都应该是未编辑的。

这是一个有效的例子:

$text = 'This is a test to remove single lines.<br />
The line below has the open type bbcode (case insensitive) that is to be removed.<br />
The text on the same line that follows the bbcode should also be removed.<br />
this text should remain[test]this text should be removed on this line only!<br />
the other lines should remain.<br />
done.<br />';

$remove = '[test]';
$lines = preg_split('/\r?\n/', $text);
foreach ($lines as $line)
{
    $check = substr($line, 0, stripos($line, $remove));
    $new[] = !empty($check) ? $check . '<br />' : $line;
}

$newText = implode($new);

echo $newText;

上面的代码按预期工作,但我想知道如何使用正则表达式或者使用少量代码和内存的东西。我试图使用此站点上的示例使用正则表达式进行此操作+一些修补但无法获得所需的结果。该解决方案还应使用与PHP 5.5语法兼容的代码(无\ e修饰符)。使用数组作为删除模式也是合适的,因为我可能需要搜索多个模式(虽然在我的示例中没有显示)。

谢谢。


感谢frightangel向我展示了正确的正则表达式模式。

以下是完成上述要求的必要代码:

$text = 'This is a test to remove single lines.<br />
The line below has the open type bbcode (case insensitive) that is to be removed.<br />
The text on the same line that follows the bbcode should also be removed.<br />
this text should remain[test]this text should be removed on this line only!<br />
the other lines should remain.<br />
[bbc]done.<br />
[another]this line should not be affected.<br />
it works!!<br />';

$removals = array('[test]', '[bbc]');
$remove = str_replace(array('[', ']'), array('~\[', '\].*?(?=\<br\s\/\>|\\n|\\r)~mi'), $removals);  
$text = preg_replace($remove, '', $text);

echo $text;

它搜索的文本实际上来自一个提供数组的mysql查询,因此我更改了上面显示的内容,以便使用或多或少使用的内容($ removals是该数组)。

我唯一的问题是,如果文本在删除之前,那么最好从该行留下最后的换行符而不是省略它。如果删除了单行中的所有文本,则只应省略它。

2 个答案:

答案 0 :(得分:0)

试试这个,并告诉我这是不是你想要的 如果没有,告诉我,我可能不理解你的问题

 preg_replace("/\[\S+\].+<[^>]+\s?\/>|<[^>]+\s?\/>/m","",$text);

答案 1 :(得分:0)

尝试这种方式:

$text = 'This is a test to remove single lines.<br />
The line below has the open type bbcode (case insensitive) that is to be removed.<br />
The text on the same line that follows the bbcode should also be removed.
this text should remain[test]this text should be removed on this line only!<br />
the other lines should remain.<br />
done.<br />';

$remove = 'test';

$text = preg_replace("/\[$remove\].*(?=\<br\s\/\>)/m", '', $text);
$text = preg_replace("/^(\<br\s\/\>)|(\\n)|(\\r)$/m","",$text);

echo $text;

这是正则表达式的解释:http://regex101.com/r/nW1bG8