【问题标题】:How to str_replace text conditionally with if/not如何用 if/not 有条件地替换文本
【发布时间】:2020-11-12 13:22:24
【问题描述】:

在抓取网页的 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);

【问题讨论】:

  • 如果href="/ 但如果href=/ 如果没有引号,你怎么知道href?
  • 否则就是href="?/(?!/)
  • $html = str_replace('href="?/(?!/)', $url, $html); 没有做任何事情。

标签: php regex str-replace


【解决方案1】:

您需要使用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=//

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 2018-08-28
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多