将字符串中除以 "http" 或 "https" 开头的所有匹配项替换为 php

Replace all occurences in string except the ones starting with "http" or "https" with php

我正在尝试在 php 中编写一个函数,我想用“http://www”替换所有出现的 "www."。

$text = preg_replace("www\.", "http://www.", $data);

我试过使用此代码,但我不想要字符串“http://www”。将变成“http://http://www”。

有什么建议吗?

^ 锚点添加到您的正则表达式中:

$text = preg_replace("/^www\./", "http://www.", $data);
                       ^ -- this one

注意:注意模式参数中的正则表达式分隔符 (/.../)。

这个行首锚点有助于确保要替换的 www. 字符串位于 $data 字符串的开头。它将防止在这样的字符串中间进行任何不需要的替换:redirector.com/?www.whosebug.com

你可以通过消极的回顾来实现:

'~(?<!://)www\.~'

regex demo

如果 www. 前面有 ://,则 (?<!://) 后视将导致匹配失败,从而避免 http://www.https://www. 中的匹配。

如果您真的想避免匹配只有 http:// 的字符串,请在 : 之前添加 http\bhttp 并使用 '~(?<!http://)www\.~'

试试这个。这不仅会检查 HTTP,还会检查其他协议,如 HTTPS、FTP 等

function addPrefix($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

echo addPrefix("http://ww.google.com");

你可以试试负面回顾:

(?!http://)www\.

试试这个简化的代码

 i.e  $url='www.xyz.com';
            function urlModified($patterns, $replace, $url)
            {
              $patterns = array ('http://www.');
              $replace = array ('/^www\./');
              preg_replace($patterns, $replace, $url);
              return $url;
            }