如何在 preg_split() 中使用多个分隔符

问题描述 投票:0回答:1

我有这个 preg_split 函数,其模式可以搜索任何

<br>

但是,除了

<br>
之外,我还想添加一些更多的图案。

如何使用下面当前的代码行来做到这一点?

preg_split('/<br[^>]*>/i', $string, 25);
php delimiter preg-split
1个回答
1
投票

PHP 的

preg_split()
函数仅接受单个模式参数,而不接受多个。因此,您必须使用正则表达式的强大功能来匹配您的分隔符。

这是一个例子:

preg_split('/(<br[^>]*>)|(<p[^>]*>)/i', $string, 25);

如果匹配 HTML 换行符 和/或 段落标记。

使用正则表达式工具来测试表达式很有帮助。本地服务或基于网络的服务,例如 https://regex101.com/

上面是示例文本

this is a <br> text
with line breaks <br /> and
stuff like <p>, correct?

像这样:

Array
(
    [0] => this is a
    [1] =>  text
with line breaks
    [2] =>  and
stuff like
    [3] => , correct?
)

但请注意,对于解析 HTML 标记,DOM 解析器可能是更好的选择。您不会冒被转义字符等绊倒的风险...

© www.soinside.com 2019 - 2024. All rights reserved.