我有下面的代碼,它應該使純文本鏈接可點擊。但是,如果有多個鏈接,它只會替換最後一個鏈接。preg_match_all和foreach只替換最後的匹配
代碼:
$nc = preg_match_all('#<pre[\s\S]*</pre>#U', $postbits, $matches_code);
foreach($matches_code[0] AS $match_code)
{
$match = null;
$matches = null;
$url_regex = '#https?://(\w*:\w*@)?[-\w.]+(:\d+)?(/([\w/_.]*(\?\S+)?)?)?[^<\.,:;"\'\s]+#';
$n = preg_match_all($url_regex, $match_code, $matches);
foreach($matches[0] AS $match)
{
$html_url = '<a href="' . $match . '" target="_blank">' . $match . '</a>';
$match_string = str_replace($match, $html_url, $match_code);
}
$postbits = str_replace($match_code, $match_string, $postbits);
}
結果:
http://www.google.com
http://www.yahoo.com
http://www.microsoft.com/ <-- only this one is clickable
預期結果:
我的錯誤在哪裏?
什麼的'[\ S \ S]'點?這匹配一切,就像'.'。如果問題在於它不符合換行符,使用's'修飾符。 – Barmar