需要帮助来提出正则表达式将其转换为链接

时间:2011-06-29 06:20:23

标签: php regex

我需要将以下内容转换为链接:

  

<一个   HREF =“http://maps.google.com/maps?um=1&ie=UTF-8&q=little+river+canyon+center&fb=1&gl=us&hq=little+river+canyon + center& hnear = 0x888a614b2e7272e5%3A0x913a5fafeec714d6%2CCentre%2C + AL& ei = GBsFTtedF8vUgAfex6zNAQ& sa = X& oi = local_group& ct = image& ved = 0CAQQtgM< br“target =”_ blank“> http:// maps。 google.com/maps?um=1&ie=UTF-8&q=little+river+canyon+center&fb=1&gl=us&hq=little+river+canyon+center&hnear=0x888a614b2e7272e5%3A0x913a5fafeec714d6% 2CCentre%2C + AL&安培; EI = GBsFTtedF8vUgAfex6zNAQ&安培; SA = X&安培; OI = local_group&安培; CT =图像&安培; VED = 0CAQQtgM&LT峰; br< / A>   />

这是我目前使用的正则表达式不起作用:

$hike_description = preg_replace('#([\s|^])(www)#i', '$1http://$2', $hike_description);
$pattern = '#((http|https|ftp|telnet|news|gopher|file|wais):\/\/[^<\s]+)#i';
$replacement = '<a href="$1" target="_blank">$1</a>';
$hike_description = preg_replace($pattern, $replacement, $hike_description);

远足描述是我需要在链接中创建的文本。

2 个答案:

答案 0 :(得分:1)

首先尝试修剪“/&gt;”

 $hike_description="http://maps.google.com/maps?um=1&ie=UTF-8&q=little+river+canyon+center&fb=1&gl=us&hq=little+river+canyon+center&hnear=0x888a614b2e7272e5%3A0x913a5fafeec714d6%2CCentre%2C+AL&ei=GBsFTtedF8vUgAfex6zNAQ&sa=X&oi=local_group&ct=image&ved=0CAQQtgM />";

$hike_description =trim($hike_description,"/>");


$hike_description = preg_replace('#([\s|^])(www)#i', '$1http://$2', $hike_description);
$pattern = '#((http|https|ftp|telnet|news|gopher|file|wais):\/\/[^<\s]+)#i';

$replacement = '<a href="$1" target="_blank">$1</a>';
$hike_description = preg_replace($pattern, $replacement, $hike_description);

答案 1 :(得分:1)

在编辑过的问题中,这已经不是很清楚了,但是从最初的问题来看,我猜这里的整个问题是链接以<br结尾,这在HTML中是不合法的。

尝试在$ hike_description上使用htmlspecialchars