2011-11-22 106 views
-1

這是另一篇文章here的後續文章。使用正則表達式轉義字符串中的雙引號

問題:下面的代碼工作良好,包含雙引號將呈現奇怪的字符

弦外

樣品字符串:

「Walter Isaacson http://t.co/vaLxVduA」 

呈現爲:

「Walter Isaacson http://t.co/vaLxVduA��� 

t.co/vaLxVduA��� 

我相信問題存在於正則表達式中。我可以嘗試做什麼?

代碼:

function makeLink($match) { 
    // Parse link. 
    $substr = substr($match, 0, 6); 
    if ($substr != 'http:/' && $substr != 'https:' && $substr != 'ftp://' && $substr != 'news:/' && $substr != 'file:/') { 
     $url = 'http://' . $match; 
    } else { 
     $url = $match; 
    } 

    return '<a href="' . $url . '">' . $match . '</a>'; 
} 
function makeHyperlinks($text) { 
    // Find links and call the makeLink() function on them. 
    return preg_replace('/((www\.|http|https|ftp|news|file):\/\/[\w.-]+\.[\w\/:@=.+?,#%&~-]*[^.\'# !(?,><;\)])/e', "makeLink('$1')", $text); 
} 
+0

什麼是「preg_replace」?你爲什麼在引號中傳遞正則表達式?函數調用? – Pointy

+1

@Pointy:你認真嗎? '的preg_replace()'是做一個正則表達式替換操作的PHP函數,正則表達式文字裏面有在PHP引號傳遞。 –

回答

0

的問題是模具Unicode字符。當您添加umodifier時,要將每個字符串視爲UTF-8,它將起作用,但也會將引用作爲URL的一部分加以捕獲。您需要排除這句話也:

preg_replace('/((www\.|http|https|ftp|news|file):\/\/[\w.-]+\.[\w\/:@=.+?,#%&~-]*[^.\'# !(?,>」<;\)])/eu', "makeLink('$1')", $text); 

但是你的正則表達式看起來有點龐大,我做了一個URL正則表達式和found this一個快速搜索,它似乎也工作,並不需要所有的排除

preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@eu', "makeLink('$1')", $text); 
+0

非常感謝。第一個正則表達式不起作用,但第二個正常。 – Codex73

相關問題