如果链接没有,请将http://添加到链接中';我没有


Add http:// to a link if it doesn't have it

我有一个非常简单的url-bbcoder,我想调整它,所以如果链接不包含用于添加它的http://,我该怎么做?

    $find = array(
    "/'[url'=(.+?)'](.+?)'['/url']/is",
    "/'[url'](.+?)'['/url']/is"
    );
    $replace = array(
    "<a href='"$1'" target='"_blank'">$2</a>",
    "<a href='"$1'" target='"_blank'">$1</a>"
    );
    $body = preg_replace($find, $replace, $body);

您可以使用(http://)?来匹配http://(如果存在),并在"替换为"模式中忽略组结果,使用您自己的http://,如下所示:

$find = array(
"/'[url'=(http://)?(.+?)'](.+?)'['/url']/is",
"/'[url'](http://)?(.+?)'['/url']/is"
);
$replace = array(
"<a href='"http://$2'" target='"_blank'">$3</a>",
"<a href='"http://$2'" target='"_blank'">$2</a>"
);
$body = preg_replace($find, $replace, $body);
if(strpos($string, 'http://') === FALSE) {
    // add http:// to string
}
// I've added the http:// in the regex, to make it optional, but not remember it,
// than always add it in the replace
$find = array(
    "/'[url'=(?:http://)(.+?)'](.+?)'['/url']/is",
    "/'[url'](.+?)'['/url']/is"
    );
    $replace = array(
    "<a href='"http://$1'" target='"_blank'">$2</a>",
    "<a href='"http://$1'" target='"_blank'">http://$1</a>"
    );
    $body = preg_replace($find, $replace, $body);

如果要使用回调函数和preg_replace_callback(),则可以使用以下内容:你可以这样做。它将始终添加"http://",而不是没有"http://"的字符串

$string = 'http://'. str_replace('http://', '', $string);