PHP正则表达式在DOM中查找并替换url属性

时间:2013-05-05 03:00:34

标签: php regex dom

目前我有以下代码:

    //loop here 
    foreach ($doc['a'] as $link) {
        $href = pq($link)->attr('href');                
        if (preg_match($url,$href))
        {
            //delete matched string and append custom url to href attr
        }       
        else
        {
            //prepend custom url to href attr
        }
    }
    //end loop

基本上我已经取出了小瓶卷曲外部页面。我需要将自己的自定义URL附加到DOM中的每个href链接。我需要检查通过正则表达式,如果每个href attr已经有一个基本网址,例如www.domain.com/MainPage.html/SubPage.html

如果是,请将www.domain.com部分替换为我的自定义网址。

如果没有,那么只需将我的自定义网址附加到相对网址即可。

我的问题是,我应该使用什么正则表达式语法和哪些php函数? preg_replace()是否适用于此功能?

干杯

1 个答案:

答案 0 :(得分:2)

您应尽可能使用内部而不是REGEX,因为这些函数的作者通常会考虑边缘情况(或阅读详述所有情况的REALLY long RFC for URLs)。对于你的情况,我会使用parse_url()然后http_build_url()(注意后一个函数需要PECL HTTP,可以通过the docs page for the http package来安装):

$href = 'http://www.domain.com/MainPage.html/SubPage.html';
$parts = parse_url($href);

if($parts['host'] == 'www.domain.com') {
    $parts['host'] = 'www.yoursite.com';

    $href = http_build_url($parts);
}

echo $href; // 'http://www.yoursite.com/MainPage.html/SubPage.html';

使用您的代码的示例:

foreach ($doc['a'] as $link) {
    $urlParts = parse_url(pq($link)->attr('href'));               

    $urlParts['host'] = 'www.yoursite.com'; // This replaces the domain if there is one, otherwise it prepends your domain

    $newURL = http_build_url($urlParts);

    pq($link)->attr('href', $newURL);
}