【问题标题】:PHP Reg ex for parsing a link用于解析链接的 PHP 正则表达式
【发布时间】:2010-11-21 18:16:44
【问题描述】:

我有一个 PHP 脚本,它解析表单(消息)的 POST 内容并将任何 URL 转换为真正的 HTML 链接。这是我使用的 2 个正则表达式:

$dbQueryList['sb_message'] = preg_replace("#(^|[\n ])([\w]+?://[^ \"\n\r\t<]*)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $dbQueryList['sb_message']);

$dbQueryList['sb_message'] = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $dbQueryList['sb_message']);

好的,但现在,在另一个脚本中,我想做相反的事情。所以在我的$dbQueryList['sb_message'] 中,我可以有一个像“&lt;a href="http://google.com" target="_blank"&gt;Google&lt;/a&gt;”这样的链接,我只想有一个“http://google.com”。

我无法编写可以做到这一点的正则表达式。请问你能帮帮我吗? 谢谢:)

【问题讨论】:

    标签: php regex parsing hyperlink


    【解决方案1】:

    我认为是这样的:

    echo preg_replace('/<a href="([^"]*)([^<\/]*)<\/a>/i', "$1", 'moofoo <a href="http://google.com" target="_blank"> Google </a> helloworld');
    

    【讨论】:

      【解决方案2】:

      使用DOMDocument而不是正则表达式来解析HTML内容更安全。

      试试这个代码:

      <?php
      
      function extractAnchors($html)
      {
          $dom = new DOMDocument();
          // loadHtml() needs mb_convert_encoding() to work well with UTF-8 encoding
          $dom->loadHtml(mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8"));
      
          $xpath = new DOMXPath($dom);
      
          foreach ($xpath->query('//a') as $node)
          {
              if ($node->hasAttribute('href'))
              {
                  $newNode = $dom->createDocumentFragment();
                  $newNode->appendXML($node->getAttribute('href'));
                  $node->parentNode->replaceChild($newNode, $node);
              }
          }
      
          // get only the body tag with its contents, then trim the body tag itself to get only the original content
          return mb_substr($dom->saveXML($xpath->query('//body')->item(0)), 6, -7, "UTF-8");
      }
      
      $html = 'Some text <a href="http://www.google.com">Google</a> some text <img src="http://dontextract.it" alt="alt"> some text.';
      echo extractAnchors($html);
      

      【讨论】:

        猜你喜欢
        • 2010-09-05
        • 2018-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-02
        相关资源
        最近更新 更多