【问题标题】:Split sentence(HTML code) into words by spaces and brackets通过空格和括号将句子(HTML代码)拆分为单词
【发布时间】:2015-06-10 10:02:03
【问题描述】:

例如我想拆分以下 HTML 代码:

<a href="http://www.google.com">Google</a>

输出应该用空格和尖括号分隔

Array(
[0] => <
[1] => a
[2] => href="http://www.google.com"
[4] => >
[5] => Google
[6] => <
[7] => /a
[8] => >

【问题讨论】:

  • 你尝试了吗?
  • 我用这个用空格分隔 $split = preg_split("/[^\w]*([\s]+[^\w]*|$)/", $sentence, - 1, PREG_SPLIT_NO_EMPTY);

标签: php regex string preg-split


【解决方案1】:

不确定您要达到什么目的,但对于您的示例,您可以使用选项 PREG_SPLIT_DELIM_CAPTURE 在结果中包含捕获的分隔符部分:

$result = preg_split('/([<>])| /', $txt, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

【讨论】:

  • 谢谢!像魅力一样工作。
  • @Rishi:这样做的目的是什么?
  • 开发一个脚本来识别 html 页面类型。 (即广告页与否)
【解决方案2】:
>>> '<a href="http://www.google.com">Google</a>'
    .match(/(<)(\w+)\s+(href=\"[\w\/:.]+\")\s*(>)(.*)?(<)(\/\w)(>)/)

 ["<a href="http://www.google.com">Google</a>" 
  ,"<", "a", "href="http://www.google.com"", ">", "Google", "<", "/a", ">"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 2012-11-16
    • 1970-01-01
    相关资源
    最近更新 更多