在获取PHP正则表达式时遇到问题

时间:2011-01-01 23:29:16

标签: php regex preg-replace

这是我的问题。这可能是一个简单的修复。我有一个正则表达式,我用来替换网址BBCode。我现在所做的不起作用就像这样。

<?php
$input_string = '[url=www.test.com]Test[url]';
$regex = '/\[url=(.+?)](.+?)\[\/url]/is';
$replacement_string = '<a href="$1">$2</a>';
echo preg_replace($regex, $replacement_string, $input_string);
?>

这当前输出原始的$ input_string,而我希望它输出以下内容。

<a href="www.test.com">Test</a>

我错过了什么?

2 个答案:

答案 0 :(得分:3)

<?php
$input_string = '[url=www.test.com]Test[/url]';
$regex = '/\[url=(.+?)\](.+?)\[\/url\]/is';
$replacement_string = '<a href="$1">$2</a>';
echo preg_replace($regex, $replacement_string, $input_string);
?>
  • 在你的BBCode字符串中,我关闭了 [url]正确。{/ li>
  • 我在正则表达式中逃过](不确定这是否是实际问题)。

请注意,[url]http://example.org[/url]也是在BBCode中建立链接的有效方式。

您应该听取建议您使用现有BBCode解析器的评论。

答案 1 :(得分:0)

更改此行如下: $regex = '/[url=(.+?)](.+?)[url]/is';

ON,格式化不正确。虽然我弄清楚了,但请看:http://pastebin.com/6pF0FEbA