PHP从字符串中删除整个单词(如果包含)


PHP remove entire word from string if contains

我有显示我的推文的代码。在推特中,图片和链接都显示为网址。如果是图片或链接,我想删除整个"WORD"。PS我在这里发现了一些线程,它们接近我想要的,但并没有产生我想要的效果。

如果它包含一个"http"或".pic",那么我想删除整个"word"。

这是我的代码:

<?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

预期结果:这条推文有一个和一个url

澄清更新:
我想删除任何包含".pic"或"http"的"无空格字符串"。我不知道如何用正确的术语来解释。。。但如果我的推文中有一个.pic.twitter.com/ia8akd,我希望整件事都消失。与任何包含"http"的内容相同。我希望整根"绳子"都没了。例如,我的推文是"这是我的网站:http://www.MyWebsite.com.很酷?我想把它显示为"这是我的网站:很酷吗?"?"

'w.:不匹配。您应该匹配单词周围的所有连续非空白字符。

'S*(?:http|pic)'S*

这将删除以pic开头的任何内容,但它不是特定于URL的。

Regex演示: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;

您可以使用此。。。

https://eval.in/611119

$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$值,并在生成的阵列上使用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} "));