【问题标题】:PHP regex find and replace url attributes in DOMPHP 正则表达式在 DOM 中查找和替换 url 属性
【发布时间】:2013-04-29 03:49:10
【问题描述】:

目前我有以下代码:

    //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

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

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

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

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

干杯

【问题讨论】:

    标签: php regex dom


    【解决方案1】:

    您应该尽可能使用内部而不是 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);
    }
    

    【讨论】:

    • 其实我只是想到了什么。我的自定义 url 不是静态的,即它将取决于用户输入并存储在变量中。 preg_replace 是否能够获取存储在变量中的 url,将其与另一个 url 进行比较并用我自己的 url 替换匹配的 url?
    • 使用它不需要是静态的。您可以将其与 foreach 循环一起使用。让我重申一下,我建议反对使用preg_replace()
    • 我只是仔细地重新阅读了你的答案,哇,这真的是我需要的!哈哈对不起我的不好,我一定是因为太多的编码太累了。我现在会尽快尝试该方法,并尽快回来:)
    • 我正在尝试获取 PECL HTTP 扩展,在 php 手册站点上它只解释了如何为 Windows 安装它。我使用的是 Mac,我在这里读到 stackoverflow.com/questions/5536195/… 我应该下载并安装 PEAR?我以前从未安装过任何 php 扩展,您有什么建议可以在 mac 上获取 PECL HTTP 吗?
    • 你签出了吗:pear.php.net/manual/en/…?
    猜你喜欢
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 2015-03-25
    相关资源
    最近更新 更多