2011-08-31 22 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

相關問題