php - 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 社区中是否有人知道我做错了什么,如果知道,可以解释我做错了什么?
提前致谢。
解决方案
首先,使用正则表达式解析 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
至于您当前的错误,您已定义/
为正则表达式模式的分隔符。这意味着如果您想使用文字正斜杠,则必须转义它(就像您使用正则表达式元字符一样)。
推荐阅读
- mysql - 使用 INDEX 优化 SQL 查询
- java - 自动向下滚动 textarea JAVA(并将图像添加到特定区域)
- php - quoted_printable_decode 一些带重音的单词返回 �
- c# - ExecuteAsync 不会将控制权返回给调试器
- i18next - 如何使用不同的语言环境调用 i18next.tr 函数?
- sql-server - 在 SQL Server 中对 SQLCLR 程序集进行逆向工程
- python - 获取另一个系列中系列的出现次数
- mysql - 内连接不使用覆盖索引
- python - 将 pandas 数据帧转换为 parquet 格式并上传到 s3 存储桶
- typescript - "schemaName"."tableName" 生成 "schemaName.tableName" - Sequelize - Postgres