首页 > 解决方案 > 如何用 if/not 有条件地替换文本

问题描述

抓取网页的 html 后,我需要有条件地替换文本以更正指向资源和媒体的链接。

我需要通过将 'href="/' 替换为 'href="http://example.com/' 来替换本地链接,这样链接才能正常工作,但同时排除诸如 'href="//' 之类的任何内容链接到不使用“http:/https:”的非现场资源以兼容和不兼容 SSL。所以......

如果 'href="/' 或 'href=/'

但如果 'href="//' 或 'href=//' 则不是

这并没有取代任何东西......

   $html = str_replace('href="?/(?!/)', $url, $html);

同时,我首先替换//:

    $html = str_replace('href="//', 'href="https://', $html);
    $html = str_replace('href=//', 'href=https://', $html);

标签: phpregexstr-replace

解决方案


您需要preg_replace用于正则表达式替换,而不是str_replace

$tests = array("<a href=\"/",  "<a href=/", "<a href=\"//", "<a href=//");

$pattern = '/href=("?)\/(?!\/)/';

foreach ($tests as $test) {
  echo preg_replace($pattern, "href=\\1http://example.com/", $test);
  echo "\n";
}

输出:

<a href="http://example.com/
<a href=http://example.com/
<a href="//
<a href=//

演示


推荐阅读