使用正则表达式提取链接

时间:2014-11-03 12:01:44

标签: php regex

我有特定的行会出现在textarea的帖子中,我需要提取它们并将它们转换为链接。如果id只是一个数字,我之前的示例中的PHP代码可以正常工作,但我现在需要它来处理可能包含字母,数字,短划线和正向斜线的网址

$pattern = '/@\[([^\]]+)\]\(id:(\d+)\)/';
$replacement = '<a href="link/$2">$1</a>';
$text = preg_replace($pattern, $replacement, $text);

模式匹配除url之外的所有内容。如何将\ d +更改为我需要的内容。我认为\ w可能有效,但它没有。

@[Lucy Lawless](id:residential-lettings/landlords/view/landlord/161)将成为<a href="residential-lettings/landlords/view/landlord/161">Lucy Lawless</a>

@[200 Daly Park ](id:residential-lettings/properties/view/property/257)将成为<a href="residential-lettings/properties/view/property/257">200 Daly Park</a>

@[Courrrty](id:residential-lettings/supplier/view/supplier/7)将成为<a href="residential-lettings/supplier/view/supplier/7">Courrrty</a>

2 个答案:

答案 0 :(得分:1)

如下所示更改正则表达式

@\[([^\[\]]+)\]\(id:([^()]*)\)

然后将匹配替换为<a href="$2">$1</a>

DEMO

[^()]*匹配任何字符,但不匹配()零次或多次。

$pattern = '~@\[([^\[\]]+)\]\(id:([^()]*)\)~';
$replacement = '<a href="$2">$1</a>';
$text = preg_replace($pattern, $replacement, $text);

答案 1 :(得分:0)

\[([^\]]+)\]\(id:(.*?\d+)\)

试试这个。参见demo.Replace by <a href="link/$2">$1</a>

刚刚将\d+更改为.*?\d+,以便它包含所有\d+

参见演示。

http://regex101.com/r/tF4jD3/12

$re = "/\\[([^\\]]+)\\]\\(id:(.*?\\d+)\\)/m";
$str = "[Lucy Lawless](id:residential-lettings/landlords/view/landlord/161)\n[200 Daly Park ](id:residential-lettings/properties/view/property/257)";
$subst = "<a href=\"link/$2\">$1</a>";

$result = preg_replace($re, $subst, $str);