【问题标题】:Split text into smaller parts identified by needle将文本拆分为针识别的较小部分
【发布时间】:2017-07-29 16:31:50
【问题描述】:

我想像这样拆分一个字符串:

'This <p>is</p> a <p>string</p>'

我想得到 4 个字符串:

  • 这个

  • &lt;p&gt;is&lt;/p&gt;

  • 一个
  • &lt;p&gt;string&lt;/p&gt;

所以我想找到&lt;p&gt;&lt;/p&gt;和它的内容一一进行拆分。我怎样才能保持相同的顺序?

我可以使用该代码获得“这个”:$html1 = strstr($html, '&lt;p', true);,但我不知道如何继续拆分以及如何为具有许多针(至少 2 个不同的针)的可变字符串进行拆分。你能帮我吗?

【问题讨论】:

  • 只有p标签是这样吗?
  • 如果你只想要你的p标签,你可以使用捕获&lt;p&gt; * &lt;/p&gt;的正则表达式分割你的字符串
  • 我建议你想出一些可以使用捕获组的正则表达式来实现的规则。
  • 对于解析 HTML 字符串,您可能需要考虑 converting to a DOM 并使用 PHP 的内置工具。
  • 不只是在空格上分割吗? 3v4l.org/afmZt

标签: php split


【解决方案1】:

您可以将preg_split 与一些选项一起使用($s 是输入字符串):

preg_split("#\s*(<p>.*?</p>)\s*#", $s, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

这将返回一个数组。对于您的示例输入,它返回:

["This", "<p>is</p>", "a", "<p>string</p>"]

看到它在repl.it上运行

【讨论】:

  • 这是一个很好的解决方案。没想到preg_split这么厉害。请注意,您不需要转义 /,因为您使用 # 作为正则表达式结束括号。
  • 谢谢,@BeetleJuice。删除了转义。
【解决方案2】:

因为你的针很复杂,你可以使用preg_match_all

$html = 'This <p>is</p> a <p>string</p>';

// Regex to group by paragraph and non-paragraph
$pattern = '/(.*?)(<p>.+?<\/p>)/';

// Parse HTML using the pattern and put result in $matches
preg_match_all($pattern,$html,$matches, PREG_SET_ORDER);

// Will contain the final pieces
$pieces = [];

// For each $match array, the 0th member is the full match
// every other member is one of the pieces we want
foreach($matches as $m) while(next($m)) $pieces[] = trim(current($m));

print_r($pieces);// ['This', '<p>is</p>', 'a', '<p>string</p>']

Live demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    相关资源
    最近更新 更多