用于将URL和标记转换为锚点的标记

时间:2013-11-06 07:25:24

标签: javascript php regex hyperlink

如何更改此类链接

http://someaddr.ess/linked [URL NAME]

进入

<a href="http://someaddr.ess/linked">URL NAME</a>

我正在寻找PHP或jQuery的解决方案。

* 我没有在stackoverflow中找到特别针对此的解决方案。如果您已经知道了一些答案,请链接到它。

3 个答案:

答案 0 :(得分:4)

试试这段代码:

$a =  'http://someaddr.ess/linked [URL NAME]';
echo preg_replace('~(https?://\S+)\s*\[([^\]]+)\]~', '<a href="$1">$2</a>', $a);
//=> <a href="http://someaddr.ess/linked">URL NAME</a>

答案 1 :(得分:1)

你能试试吗,

<?php
    $input ="http://someaddr.ess/linked [URL NAME]";
    $input =str_replace("]", "", $input);
    list($url, $URLTEXT) =explode("[", $input);

    $URL = preg_replace('!(http|ftp|scp)(s)?:\/\/[a-zA-Z0-9.?&_/]+!', "<a href=\"\\0\">".$URLTEXT."</a>",$url);     

    echo $URL;
 ?>

答案 2 :(得分:0)

尝试

$str = "http://someaddr.ess/linked [URL NAME]";
$new_arr = explode(' ',$str);

preg_match_all('/\[([A-Za-z]+?)\]/', $str, $text);
echo "<a href='".$new_arr[0]."'>".$text[0]."</a>";