首页 > 解决方案 > PHP preg_match_all(): 未知修饰符 '>'

问题描述

我正在尝试创建一个正则表达式来过滤掉 PHP 中的 HTML 开始标签

到目前为止,我想出了这个模式/\<[^/>]*\>/。这种模式似乎适用于https://regexr.com/49vgk

但是,一旦我将其复制到 PHP 中,我就会收到此错误: PHP preg_match_all(): Unknown modifier '>'

PHP代码:

$input = '<p>This is my HTML text that I want <b>all</b> opening tags from</p>';

$regexPattern = '/\<[^/>]*\>/';
$openingTags = preg_match_all($regexPattern, $input);

到目前为止,我无法弄清楚是什么导致了这个问题。主要是因为我已经逃脱了大多数角色。

StackOverflow 社区中是否有人知道我做错了什么,如果知道,可以解释我做错了什么?

提前致谢。

标签: phpregex

解决方案


首先,使用正则表达式解析 HTML 是邪恶的。

现在这已经不碍事了,这是一个工作脚本:

$input = '<p>This is my HTML text that I want <b>all</b> opening tags from</p>';
$regexPattern = '/<[^\/][^>]*>/';
preg_match_all($regexPattern, $input, $matches);
print_r($matches[0]);

Array
(
    [0] => <p>
    [1] => <b>
)

这是模式的解释<[^\/][^>]*>

<      match an opening bracket
[^\/]  match a single character other than /
[^>]*  then match zero or more non closing bracket characters
>      match a closing bracket

至于您当前的错误,您已定义/为正则表达式模式的分隔符。这意味着如果您想使用文字正斜杠,则必须转义它(就像您使用正则表达式元字符一样)。


推荐阅读