如何使用正则表达式在链接标签中获取文本


PHP: How to use Regex to obtain text within link tags

我想获得这些链接标签中的文本:

<a target="_blank" class="timestamp" href="http://www.link.com/1">10:55 am</a>
<a target="_blank" class="timestamp" href="http://www.link.com/2">3:30 pm</a>

到目前为止,我有:

preg_match_all('/<a (.*?)<'/a>/s', $html, $matches);
print_r($matches[1]);
不幸的是,它返回两个a之间的所有内容。是否有一种方法可以在a标签之间获取文本,意味着上午10:55和下午3:30 ,而不是其他?

应该可以。不过,您可以考虑使用XPath之类的东西。

preg_match_all('/<a[^>]*>(.*?)<'/a>/s', $html, $matches);