代码之家  ›  专栏  ›  技术社区  ›  paulobunga

php使用preg_replace替换curl响应中出现的多个域

  •  0
  • paulobunga  · 技术社区  · 6 年前

    如何使用php中的preg_replace,使用正则表达式在href标记中更改域的多次出现。

    我只需要链接的相对路径。我拥有的代码将删除所有内容,包括URL路径和查询参数。

    当前链接外观

    <a href="https://www.website.com/LUGAD-Clothing-Jewelry-Shoulder-Brushed/dp/B07D1V99MF/ref=sr_1_3/131-4937141-2376367/s=apparel&ie=UTF8&qid=1531422091&sr=1-3&nodeID=7141123011&psd=1&keywords=clothing%2Cshoes+and+jewelry">The Link</a>
    

    期望的链接外观

    <a href="/LUGAD-Clothing-Jewelry-Shoulder-Brushed/dp/B07D1V99MF/ref=sr_1_3/131-4937141-2376367/s=apparel&ie=UTF8&qid=1531422091&sr=1-3&nodeID=7141123011&psd=1&keywords=clothing%2Cshoes+and+jewelry">The Link</a>
    

    我试过这个

    $html = $this->curl->getContent($completeUrl);
    
    $newhtml = preg_replace('/<a(.*)href="([^"]*)"(.*)>/','<a$1href="/"$3>',$html);
    

    总之。 我希望使用regex将所有出现的绝对href转换为相对href

    1 回复  |  直到 6 年前
        1
  •  1
  •   wp78de    6 年前

    从你的问题猜测,你应该使用这样的正则表达式:

    (<a\s+href\s*=\s*")(?:https?:\/\/)?www\.website\.com\/
    

    Demo

    preg_replace('/(<a\s+href\s*=\s*")(?:https?:\/\/)?www\.website\.com\//i', '$1', $str);
    

    这建立在您使用a-href作为替换锚定的想法之上。 我们不能真正使用lookbehind在URL之前断言a-href,因为在lookbehinds中可以有任意的空白,并且pcre不支持可变长度的模式。
    因此,我捕获前面的内容,并使用 $1 .

    如果您必须在 href 您可以使用:

    (<a(?:(?!href).)* href\s*=\s*")(?:https?:\/\/)?www\.website\.com\/
    

    Demo 2