0

我有这个非常简单的 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);
4

3 回答 3

4
if(strpos($string, 'http://') === FALSE) {
    // add http:// to string
}
于 2013-09-04T10:09:59.657 回答
4

您可以使用 a(http://)?来匹配http://if 存在,并忽略“替换为”模式中的组结果并使用您自己的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);
于 2013-09-04T10:16:09.740 回答
3
// 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);

If you would use a callback function and preg_replace_callback(), you can use something like this: You can do that this way. It will always add 'http://', and than the string without 'http://'

$string = 'http://'. str_replace('http://', '', $string);
于 2013-09-04T10:10:49.360 回答