PHP匹配* .domain.com

时间:2011-10-15 20:10:36

标签: php preg-match

这是我正在使用的php文件中的一些代码。我需要匹配'domain.com',但是当我输入它时它不起作用,因为它正在解析一个寻找href标签的文档,我认为它需要http://www。为了比赛。我尝试了下面的preg比赛,但它不起作用,我的编码不是很好,任何帮助将不胜感激。

preg_match(“/ domain.com/i”);

        $match = 'http://www.domain.com'; 

        for($i=0;$i<$documentLinks->length;$i++) 
        {
            $documentLink = $documentLinks->item($i);
            if ($documentLink->hasAttribute('href') AND substr(strtolower($documentLink->getAttribute('href')), 0, strlen($match)) == $match) 
            {

1 个答案:

答案 0 :(得分:3)

试试这个:

for($i=0;$i<$documentLinks->length;$i++) 
{
    $documentLink = $documentLinks->item($i);
    if ($documentLink->hasAttribute('href')) 
    {
        if (preg_match('!^https?://([^/]+\.)?domain\.com(/|#|$|\?)!i', trim($documentLink->getAttribute('href'))))
        {

正则表达式是重要的部分:

^https?://([^/]+\.)?domain\.com(/|#|$|\?)

从字符串的开头开始,匹配http或https,然后是可能不包含正斜杠的可选子域(因此您知道您仍然在域部分中),然后是您要匹配的域,然后路径的开头,片段的开头或网址的结尾