PHP 使用 preg_replace 替换 curl 响应中多次出现的域

PHP replace multiple occurrences of domain in curl response using preg_replace

如何使用 PHP 中的 preg_replace 来使用正则表达式更改 href 标签中多次出现的域。

我只需要link的相对路径。我的代码删除了所有内容,包括 url 路径和查询参数。

当前 Link 出场

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

期望 Link 出现

<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="([^"]*)"(.*)>/','<ahref="/">',$html);

综上所述。 我很想使用正则表达式将所有出现的绝对 href 转换为相对 href

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

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

Demo

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

这基于您使用 a-href 作为替换锚点的想法。 我们不能真正使用 lookbehind 在 URL 之前断言 a-href,因为可以有任意空格并且 PCRE 不支持 lookbehinds 中的可变长度模式。
因此,我捕获前面并使用 </code>.</p> 将其放回替换中 <p>如果您必须在 <code>href 之前处理其他属性,您可以使用:

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

Demo 2