2013-12-15 31 views
0

我有下面的代碼解析Twitter文字修改鏈接,提到和哈希爲超鏈接:解析Twitter文字使用PHP的preg_replace

function parseTwitterText($text) { 

    $returnText = $text; 
    $hashPattern = '/\#([A-Za-z0-9\_]+)/i'; 
    $mentionPattern = '/\@([A-Za-z0-9\_]+)/i'; 
    $urlPattern = '/(http[s]?\:\/\/[^\s]+)/i'; 
    $robotsFollow = false; 

    // SCAN FOR LINKS FIRST!!! Otherwise it will replace the hashes and mentions 
    $returnText = preg_replace($urlPattern, '\<a href\="$1" ' + (($robotsFollow)? '':'rel\=\"nofollow\"') + '\>$1\<\/a\>', $returnText); 
    $returnText = preg_replace($hashPattern, '\<a href\="http\:\/\/twitter\.com\/\#\!\/search\?q\=\%23$1" ' + (($robotsFollow)? '':'rel\=\"nofollow\"') + '\>\#$1\<\/a\>', $returnText); 
    $returnText = preg_replace($mentionPattern, '\<a href\="http\:\/\/twitter\.com\/$1" ' + (($robotsFollow)? '':'rel\=\"nofollow\"') + '\>@$1\<\/a\>', $returnText); 
    return $returnText; 
} 

不過我剛開始如果我有像鳴叫0返回#test

我基於JavaScript版本我有這個代碼,所以想知道如果我做錯了什麼在preg_replace(),只有在JS replace()

+1

以冷凝PHP字符串使用'.',而不是'+',你在JS會。 – user555

回答

3

有2個問題,在您的代碼:

  1. 在PHP中,您連接與.字符串,而不是用+。當使用+,PHP是增加他們,這導致0之前鑄造的字符串爲整數。

  2. preg_replace()電話,你不必爲了逃避第二個參數中的所有字符。所以刪除這三行中的所有反斜槓。

您應該結束了,像這樣:

$returnText = preg_replace($urlPattern, '<a href="$1" ' . (($robotsFollow)? '':'rel="nofollow"') . '>$1</a>', $returnText); 
$returnText = preg_replace($hashPattern, '<a href="http://twitter.com/#!/search?q=%23$1" ' . (($robotsFollow)? '':'rel="nofollow"') . '>#$1</a>', $returnText); 
$returnText = preg_replace($mentionPattern, '<a href="http://twitter.com/$1" ' . (($robotsFollow)? '':'rel="nofollow"') . '>@$1</a>', $returnText); 
+0

很感謝。我只是馬虎,沒有正確地改變一切。謝謝:) – Cameron

+0

從PHP 5.3.0開始,你可以忽略三元運算符的中間部分。 '($ robotsFollow)?:'rel =「nofollow」'' – user555

2

工作在PHP中,您使用.concatenate兩個字符串,不+你在JavaScript會。另外,正如BluePsyduck所提到的那樣,您不必像現在那樣逃避所有角色。

更改preg_replace()聲明如下:

$returnText = preg_replace($urlPattern, 
    '<a href="$1" ' . 
    (($robotsFollow)? '' : 'rel="nofollow"') . 
    '>$1</a>', $returnText); 

$returnText = preg_replace($hashPattern, 
    '<a href="http://twitter.com/#!/search?q=%23$1" ' . 
    (($robotsFollow)? '' : 'rel="nofollow"') . 
    '>#$1</a>', $returnText); 

$returnText = preg_replace($mentionPattern, 
    '<a href="http://twitter.com/$1" ' . 
    (($robotsFollow)? '' : 'rel="nofollow"') . 
    '>@$1</a>', $returnText); 

測試:

header('Content-Type: text/plain'); 
echo parseTwitterText('@foo lala'); 
echo parseTwitterText('#test'); 

輸出:

<a href="http://twitter.com/foo" rel="nofollow">@foo</a> lala 
<a href="http://twitter.com/#!/search?q=%23test" rel="nofollow">#test</a> 

Demo.