2011-08-31 24 views
0

我正在寻找一种php方式来搜索一个文本字符串,并将该字符串内的文本转换为链接。将特定的字符串转换为链接?

n being numbers 1-9 
Jnn:nn:nn:nn 

链接位是这样的

<a href='http://juno.astroempires.com/map.aspx?loc=Jnn:nn:nn:nn'>Jnn:nn:nn:nn</a> 

希望这是有道理的。我知道它是可能的,但我不知道该怎么做。


这是我想到了,因为我集成到现有的功能,最终的解决方案,感谢您的想法寿bumperbox和编辑Tobiask

function makeClickableLinks($text){ 
    $text = html_entity_decode($text); 
    $text = " ".$text; 
    $text = eregi_replace('(((f|ht){1}tp://)[[email protected]:%_\+.~#?&//=]+)', 
      '<a href="\\1" target=_blank>\\1</a>', $text); 
    $text = eregi_replace('(((f|ht){1}tps://)[[email protected]:%_\+.~#?&//=]+)', 
      '<a href="\\1" target=_blank>\\1</a>', $text); 
    $text = eregi_replace('([[:space:]()[{}])(www.[[email protected]:%_\+.~#?&//=]+)', 
      '\\1<a href="http://\\2" target=_blank>\\2</a>', $text); 
    $text = eregi_replace('([_\.0-9a-z-][email protected]([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})', 
      '<a href="mailto:\\1" target=_blank>\\1</a>', $text); 
    $text = eregi_replace('(J[0-9]{2}):([0-9]{2}):([0-9]{2}):([0-9]{2})', 
      '<a href="http://juno.astroempires.com/map.aspx?loc=\\1:\\2:\\3:\\4" target=_blank>\\1:\\2:\\3:\\4</a>', $text); 
    return $text; 
} 

这是在阿贾克斯/ MySQL的聊天中使用系统。我确实通过jqery完成了这项工作,但是如果我只是存储链接,用户就不那么做了。

+7

'希望这是有道理的'没有。添加一些示例从 - >对 – genesis

+0

@genesisφ 对不起,慢回复只是检查回来,那么你可以发送类似的东西。 $ string =“单词与其他一些狗屎www.link.com也在这里是像J50:45:23:23一样愚蠢的东西。 所以,当你发送srting的功能就像makeClickableLinks($字符串) 它将原来的更改为: “字与其他一些狗屎www.link.com也在这里是财产以后傻得像J50:45:23:23 我希望是有道理的成因 – Sam

回答

2

看的preg_replace

http://php.net/manual/en/function.preg-replace.php

我没有测试过这一点,但它应该是相当接近

$str = preg_replace("/(J\d{2}:\d{2}:\d{2}:\d{2})/s", "<a href="{$1}">{$1}</a>", $str); 

\ d一个数字匹配 {2}指2位

{$ 1} =在第一组内匹配的所有内容()

+0

非常感谢我正在寻找的东西 – Sam

1

使用正则表达式引擎完全是过度的。为什么不尝试这样的事情:

$url_base = 'http://juno.astroempires.com/map.aspx'; 
$loc  = 'Jnn:nn:nn:nn'; 
$parameters = array('loc' => $loc); 

$url = sprintf('<a href="%s">%s</a>', $url_base.'?'.http_build_query($parameters), $loc); 

// do whatever you need with $url 
echo $url; 
+0

在这种情况下不应该使用+1正则表达式。 – Alfwed

相关问题