2014-04-05 22 views
-1

今天我正在運行一個交友網站,爲了不失去成員,我想阻止用戶發送Facebook鏈接給對方。 他們有一個textarea他們寫對話,這是插入MySQL數據庫。現在用PHP替換帶有其他詞的鏈接

,我想,當他們寫自己的Facebook ADRESS類似的事:

https://www.facebook.com/my.nick 

與下面的文本在coversation被替換:

i like you 

任何一個優秀的PHP例子在那裏如何這可以做到? /Cheerz

+0

您已經嘗試了什麼? –

+0

我還沒有嘗試過..我想這是什麼可能是最好的解決方案..在谷歌上搜索,但還沒有發現任何東西 – Mensur

+0

嗨Mensur,我看你一直在爲網站貢獻一段時間,但閱讀一些[幫助頁面](http://stackoverflow.com/help)可能會付出代價,在這裏您可以找到一些關於如何提問符合網站格式的問題的建議。如果沒有關於您當前代碼的任何信息,以及您遇到的具體問題,則此問題不是真正的答案。 – IMSoP

回答

2

可以使用的preg_replace作爲

$str = "hello www.facebook.com. this is my fb page http://facebook.com/user-name. 
Here is another one for the profile https://www.facebook.com/my-profile/?id=123. 
"; 

$str = preg_replace('"\b((https?://|www)\S+)"', 'my new text',$str); 

echo $str ; 

output // hello my new text this is my fb page my new text 
      Here is another one for the profile my new text 

或者更好地利用與

$str = preg_replace('/\b((https?:\/\/|www)\S+)/i', 'my new text',$str); 




/\b((https?:\/\/|www)\S+)/i 

\b assert position at a word boundary (^\w|\w$|\W\w|\w\W) 
1st Capturing group ((https?:\/\/|www)\S+) 
    2nd Capturing group (https?:\/\/|www) 
     1st Alternative: https?:\/\/ 
      http matches the characters http literally (case insensitive) 
      s? matches the character s literally (case insensitive) 
       Quantifier: Between zero and one time, as many times as possible, giving back as needed [greedy] 
      : matches the character : literally 
      \/ matches the character/literally 
      \/ matches the character/literally 
     2nd Alternative: www 
      www matches the characters www literally (case insensitive) 
    \S+ match any non-white space character [^\r\n\t\f ] 
     Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy] 
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z]) 
+0

添加'http'也是一個不錯的選擇,而不只是'https',因爲如果有人要輸入'http:// www.facebook.com/whatever',是一個有效的FB地址這將重定向到「https」。另一件要考慮的事情是'http:// www.fb.com',所有沒有'www'的人都會自動重定向。你現在的代碼可能沒有考慮到這些因素; *只是說*。 ;-) –

+0

'http:// www.fb.com/whatever'會重定向到'https:// www.facebook.com/whatever',就像'http:// fb.com/whatever'一樣,所以OP可能會最終人們試圖「擊敗系統」。 –

+0

@ Fred-ii-感謝您指出了這一點,但是應該'https?'既能處理http也能處理https。可否請你給我一個字符串,將失敗的例子,以便我可以糾正上述情況。我只是添加'/我',以使它不區分大小寫,我之前錯過了。 –