我有一个用户输入字符串,其中有Stack Overflow样式的链接,像这样:
The input string [foo](http://foo.com) with a link.
,我需要转换字符串以包含锚标记,像这样:
The input string <a href="http://foo.com">foo</a> with a link.
$text = 'ignore everything except this (text)';
preg_match('#'((.*?)')#', $text, $match);
print $match[1];
但是我需要找到一种方法来匹配括号内的元素和括号内的元素。最后,用格式正确的锚标记替换整个匹配的部分。
是否有人知道正确的正则表达式语法匹配[foo](http://foo.com)
和进一步如何提取"foo"answers"http://foo.com"?
下面的正则表达式将匹配[blah](http://blah.blah)
格式的字符串。第一个[]
花括号内的字符被捕获到第1组,下一个()
花括号内的字符被捕获到第2组。之后,通过反向引用(即用'1
或'2
召回)来引用组1和组2中的字符
正则表达式:
'[([^]]*)']'(([^)]*)')
替换字符串:
<a href="'2">'1</a>
演示PHP代码应该是,
<?php
$mystring = "The input string [foo](http://foo.com) with a link";
echo preg_replace('~'[([^]]*)']'(([^)]*)')~', '<a href="'2">'1</a>', $mystring);
?>
输出:The input string <a href="http://foo.com">foo</a> with a link