1

我有一个字符串

$string = '[URL="http://www.google.com"]Google[/URL]

我正在使用以下代码将其转换为 html 链接

$link = preg_replace('/\[url=(.+?)\](.+?)\[\/url\]/i', '<a href="\1">\2</a>', $string);

它将其转换为以下格式

<a href="http://www.google.com">Google</a>

那没问题。但我想验证这两个值http://www.google.comGoogle如何在 Regex 的帮助下分别获取这两个值。

4

1 回答 1

2

我想你想要的是preg_match什么?

实际上,您可以使用已有的模式。它将通过一个参数为您提供整个匹配项以及圆括号内的每个匹配项。

preg_match('/\[url=(.+?)\](.+?)\[\/url\]/i', $string, $matches);
echo $matches[1]; // http://www.google.com
echo $matches[2]; // Google
echo $matches[0]; // [URL="http://www.google.com"]Google[/URL]

的返回值为preg_match1(找到匹配)或 0/false(无匹配/错误)。

于 2013-04-14T12:09:56.563 回答