2014-11-03 41 views
0

我有特定的行,将出现在一个文本文本的帖子中,我需要提取它们并将它们转换为链接。 PHP代码我从前面的例子有好的工作,如果ID仅仅是一个数字,但我现在就需要为可能包含字母,数字,破折号和转发URL工作削减使用正则表达式来提取链接

$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>

+0

'.'匹配任何字符。 '\ d'只匹配数字,'\ w'匹配任何字母,数字或下划线。 – Bifrost 2014-11-03 12:08:41

回答

1

改变你的正则表达式如下图所示,

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

然后更换比赛用<a href="$2">$1</a>

DEMO

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

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

谢谢,这是我改变了我的模式,现在工作$ pattern ='/ @ \ [([^ \]] +)\] \(id:([^()] *)\)/'; – 2014-11-03 12:08:04

+0

很高兴解决。 – 2014-11-03 12:10:52

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

通过<a href="link/$2">$1</a>尝试this.See demo.Replace。

刚将\d+更改为.*?\d+,以便它包含所有upto \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);