我可以使用preg_match_all()
函数计算匹配链接的数量,如下所示,它检查链接的内部文本是否等于指定的关键字。
// text contains two different links, whereby the inner
// text of the first link is capitalized and the second link starts with a small letter.
$string = "<p><a href=\"www.link1.com\" class=\"someClass\" title=\"lorem\">Lorem</a> dolor sit amet, consectetur
adipiscing elit. In iaculis, libero aliquam lacinia feugiat, <a href=\"www.link2.com\" class=\"someClass\" title=\"lorem\">lorem</a>
elit congue risus, sed sagittis turpis tortor eget orci. Integer lacinia quis nisi ac aliquet. Sed et convallis diam.</p>";
// count al matches by upper and lowercase sensitivity
preg_match_all('/<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>lorem<\/a>/siU', $string, $match);
现在我的问题是我如何制作正则表达式,以便它也能用于大写字母的匹配。
答案 0 :(得分:1)
请改用其他方法,例如使用xpath:
$xml = simplexml_load_string($string);
$links= $xml->xpath("//a");
foreach ($links as $link)
echo $link["href"];
见a demo on ideone.com。 正则表达式的解决方案是:
~(?i)href=('|")(?<link>[^'"]+)\1(?i-)~
# case-insensitive
# look for href= literally
# look for a single/double quote and capture it in group 1
# match everything that is not a singel or double quote 1 or more times
# match the first captured group again
# and turn case sensitivity on again
可以在regex101.com上找到演示,但最好使用第一种方法。