【问题标题】:php preg_match_all href inner texts with upper and lower case sensitivityphp preg_match_all href 区分大小写的内部文本
【发布时间】:2016-05-04 04:18:58
【问题描述】:

我可以使用下面的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); 

现在我的问题是如何制作正则表达式,以便它也适用于大写字母的匹配。

【问题讨论】:

标签: php regex


【解决方案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 上找到演示,但最好使用第一种方法。

【讨论】:

    猜你喜欢
    • 2019-08-19
    • 2013-02-06
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多