【问题标题】:Remove text before first occurrence of a substring在第一次出现子字符串之前删除文本
【发布时间】:2011-11-02 17:53:54
【问题描述】:

我想删除文档中第一个<tr class="vcard agent">之前的其他文本。

注意:文档中有多个<tr class="vcard agent">

【问题讨论】:

  • 举个例子看看 html 是什么样子的
  • 另外,使用更具描述性的标题。
  • @Zeta 二:我编辑了标题,但直到它被审查为止。
  • 另外,不要使用正则表达式,使用 PHP DOMDocument 类
  • 任何不使用实际 HTML 解析器的解决方案都会变得脆弱,因为有一天该页面的内容会更改为 <tr id="foo" class="vcard agent">,然后您的代码就会损坏。 htmlparsing.com/regexes.html 提供了更多示例,说明为什么正则表达式不是处理 HTML 的方法。

标签: php html regex


【解决方案1】:
$answer = strstr($oriString,'<tr class="vcard agent">');

strstrDocs

【讨论】:

    【解决方案2】:

    这样的事情可能会奏效:

    preg_replace('/.*?<tr class="vcard agent">/', '<tr class="vcard agent">', $string);
    

    编辑:Pradeep's answer 看起来是最好的。

    【讨论】:

    • 这很好,直到页面实际包含 &lt;tr id="foo" class="vcard agent"&gt; 然后代码停止工作。
    【解决方案3】:
    $first = strpos($html, '<tr class="vcard agent">');
    $result = substr($html, $first);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-15
      • 1970-01-01
      • 2018-11-21
      • 2015-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-28
      相关资源
      最近更新 更多