2017-10-19 58 views
-1

我有一些繼承的代碼,其目的是確定一個字符串中的url,如果它不存在,則會在它們前面加上http://協議。php正則表達式preg_replace_callback

return preg_replace_callback(
     '/((https?:\/\/)?\w+(\.\w{2,})+[\w?&%=+\/]+)/i', 
     function ($match) { 
      if (stripos($match[1], 'http://') !== 0 && stripos($match[1], 'https://') !== 0) { 
       $match[1] = 'http://' . $match[1]; 
      } 
      return $match[1]; 
     }, 
     $string); 

它的工作,除非域名有連字符。因此,例如,以下字符串只能部分工作。

$string = "In front mfever.com/1 middle http://mf-ever.com/2 at the end"; 

任何正則表達式天才都可以看到它有什麼問題嗎?

+1

'\ w'只能匹配字母,數字和'_'。你將需要使用允許字符的字符類。說,'[\ w-]'也匹配連字符。 –

+0

如果提供的解決方案有效,請務必接受。 – mega6382

回答

0

工作,請嘗試以下的正則表達式:

'/((https?:\/\/)?[\w-]+(\.\w{2,})+[\w?&%=+\/]+)/i', 

這將包括-了。 DEMO

相關問題