替换字符串中除了以"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.".

有什么建议吗?

添加^锚到您的regex:

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

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

这个起始行锚有助于确保要替换的www.字符串位于$data字符串的开头。它将防止在字符串中间出现任何不希望的替换,例如:redirector.com/?www.stackoverflow.com

你可以用一个消极的背影来达到这个目的:

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

查看regex演示

如果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;
            }