preg_replace无法按预期工作

时间:2012-08-21 17:52:30

标签: php regex preg-replace

我写了一个简单的函数,它接受一段文本,从中提取网址,并用它们周围的<a href>标记替换所有网址。

E.g http://site.com应成为<a href="http://site.com">http://site.com</a>

代码:

function parseUrls( $string )
{
    $string = trim($string);
    $pattern = '%\bhttp[s]?://[A-z0-9/\.\-_]+%i';
    $replacement = '<a href="$1">$1</a>';

    $string = preg_replace($pattern, $replacement, $string);

    return $string;
}

但是,如果我将以下字符串作为输入传递:

你好https://google.com测试http://test.com/something.html abc http://site.com

我得到的输出是:

hello <a href=""></a> test <a href=""></a> abc <a href=""></a> 

即匹配的网址,但$replacement未正确应用。可能是我对$1的使用在某种程度上是错误的?

我做错了什么?

3 个答案:

答案 0 :(得分:6)

您的表达式中未定义捕获组(通常由()完成)。所以$1是空的。但是$0会在替换模式中保存完整匹配字符串。

所以要么使用,

$replacement = '<a href="$0" target="_BLANK">$0</a>';

$pattern = '%\b(http[s]?://[A-z0-9/\.\-_]+)%i';
//             ^                          ^
//             |                          |
//             +-----  Capture group -----+

答案 1 :(得分:3)

您没有$1会引用的捕获组。

改为使用$replacement = '<a href="$0" target="_BLANK">$0</a>';

此外,不要在您的角色类中使用A-z(它比您想象的更匹配:ASCII Za之间有一些非字母字符)。 A-Z就足够了,因为无论如何你已经使它不区分大小写了。

答案 2 :(得分:1)

您需要使用括号对表达式进行分组才能使用$ 1。

  

$ pattern =&#39;%\ b(http [s]?:// [A-z0-9 /.-_] +)%i&#39;;