[英]PHP remove entire word from string if contains
我有代碼顯示我的推文。 在推文中,圖片顯示為網址和鏈接。 如果它是圖片或鏈接,我想刪除整個'WORD'。 PS我發現這里的線程與我正在尋找的線程很接近,但是沒有產生我想要的效果。
如果它包含“http”或“.pic”,那么我想刪除整個“單詞”。
這是我的代碼:
<?php
$wordlist = array('http','pic');
$replaceWith = "";
/* Sample data */
$words = 'This tweet has a pic.twitter.com/00GeQ3zLub and a url http://www.mywebsite.com';
foreach ($wordlist as $v)
$words = clean($v, $words, $replaceWith);
function clean($word, $value, $replaceWith) {
return preg_replace("/\w*$word\w*/i", "$replaceWith ",trim($value));
}
echo $words;
?>
實際輸出 :此推文有一個.twitter.com / 00GeQ3zLub和一個網址://www.mywebsite.com
期望的結果 :這條推文有一個和一個網址
更新澄清:
我想刪除任何包含“.pic”或“http”的“沒有空格的字符串”。 我不知道如何用正確的術語來解釋它...但如果.pic.twitter.com / ia8akd在我的推文中,我希望整件事情不復存在。 與包含“http”的任何內容相同。 我希望整個'字符串'消失了。 例如我的推文是“這是我的網站: http : //www.MyWebsite.com 。非常酷嗎?” 我希望這個顯示為“這是我的網站:很酷嗎?”
\\w
與a不匹配.
,也不是:
。 您應該匹配單詞周圍的所有連續非空白字符。
\S*(?:http|pic)\S*
這將刪除以pic
開頭的任何內容,但不是特定於URL。
正則表達式演示: https : //regex101.com/r/qZ8tD3/1
PHP演示: https : //eval.in/611103
PHP用法:
$wordlist = array('http','pic');
$replaceWith = "";
/* Sample data */
$words = 'This tweet has a pic.twitter.com/00GeQ3zLub and a url http://www.mywebsite.com';
foreach ($wordlist as $v)
$words = clean($v, $words, $replaceWith);
function clean($word, $value, $replaceWith) {
return preg_replace("/\S*$word\S*/i", "$replaceWith ",trim($value));
}
echo $words;
你可以用這個......
$wordlist = array('http','pic');
$replaceWith = "";
/* Sample data */
$words = 'This tweet has a pic.twitter.com/00GeQ3zLub and a url http://www.mywebsite.com';
foreach ($wordlist as $v)
$words = clean($v, $words, $replaceWith);
function clean($word, $value, $replaceWith) {
$reg_exUrl = "/ (".$word.")(\:\/\/|.)[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/ ";
return preg_replace($reg_exUrl,$replaceWith,trim($value));
}
echo $words;
?>
我建議你首先修剪$value
,然后使用這樣的函數:
function clean($word, $value, $replaceWith) {
$scan = preg_quote($word);
return preg_replace("#\\S{$scan}\\S#i", $replaceWith . ' ', $value);
}
這需要$ value來包含開頭和結尾的空格,因此您可以:
$value = " {$value} ";
foreach ($words as $word) {
$value = clean($word, $value, $replaceWith);
}
$value = trim($value);
您還可以在空格周圍使用preg_split
$ value並在結果數組上使用array_filter
,但此解決方案的性能可能較低。
作為優化,如果所有單詞具有相同的替換,則可以從單詞數組中組合單個正則表達式:
// So [ 'http', '.pic' ] becomes '#\\S(http|\\.pic)\\S#i'
$regex = '#\\S('
. implode('|', array_map('preg_quote', $words))
. ')\\S#i';
$value = trim(preg_replace($regex, $replaceWith . ' ', " {$value} "));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.