如果 PHP 中存在,可以选择匹配文本之间的链接和标题


Match Link and Title Between Text Optionally If Exists in PHP

我正在尝试匹配存在时的可选链接/标题,如果没有链接,只需匹配标签内的文本。

表示例:

$html_data = <<<HTML
    <table>
     <tr> <td> Some text here </td> </tr>
     <tr> <td> Some text with link <a href="http://domain1.com/">Link Title 1</a> </td> </tr>
     <tr> <td> Some text here without link </td> </tr>
     <tr> <td> Some text with link <a href="http://domain2.com/">Link Title 2</a> and more text </td> </tr>
    </table>
HTML;

代码示例:

preg_match_all('~<tr> <td> (?:<a href="(.*?)">(.*?)</a>)? (.*?) </td> </tr>~i', $html_data, $result);

所以我需要抓取纯文本和链接+标题(如果存在)并将其放在数组中。

像这样的东西,当链接存在时;

'text_before' => 'Some text with link'
'link_href' => 'http://domain2.com/'
'link_title => 'Link Title 2'
'text_after' => 'and more text'

如果没有链接,只需匹配"td"标签之间的可用文本即可。

像这样的东西,当没有链接时;

'text' => 'Some text here without link'

我会从一些步骤开始:

  1. <td.*?<'/td> 因为您需要一行带有代码来评估,然后:
  2. <a.*?>(.*?)<'/a>因为您需要链接的标题,则:
  3. href='"(.*?)'"因为您需要一个链接,然后:
  4. <td>(.*?)<因为您需要文本,即使里面没有链接,并且:
  5. <'/a>(.*?)<最后。

希望对您有所帮助。干杯。

编辑:一个正则表达式<td.*?>(.*?)(<a.*?href='"(.*?)'".*?>(.*?)</a>)?(.*?)</td>