删除字符串中的字符串


Remove strings within a string

我遇到的问题是,如果数组$wordstodelete中有单个字符,它会从$oneBigDescription中的单词中删除它们。

$oneBigDescription = str_replace ( $wordstodelete, '', $oneBigDescription);

所以它看起来像这样:

array (size=51)
  'blck' => int 5
  'centrl' => int 6
  'clssc' => int 6
  'club' => int 10
  'crs' => int 54
  'deler' => int 7
  'delers' => int 5
  'engl' => int 6
  'felne' => int 8
  'gude' => int 5
  'hot' => int 5
  'jgur' => int 172
  'jgurs' => int 5
  'lke' => int 6

有没有办法只删除$oneBigDescription中的单个字符(如果它是单独的)?

$oneBigDescription = preg_replace("/'b$wordstodelete'b/", '', $oneBigDescription);

/b应该查找单词边界,以确保在使用一个字符时它是一个孤立的单词。

编辑:没有完全读对——这更多的是假设你将$wordstodelete作为一个单词数组循环。

所以,像这样的东西:

$desc = "blah blah a b blah";
$wordstodelete = array("a", "b");
foreach($wordstodelete as $delete)
{
    $desc= preg_replace("/'b$delete'b/", "", $desc);
}

第2版:对此不太满意,所以略有改进:

$arr = "a delete aaa a b me b";
$wordstodelete = array("a", "b");
$regex = array();
foreach($wordstodelete as $word)
{
    $regex[] = "/'b$word'b's?/";
}
$arr = preg_replace($regex, '', $arr);

这说明了去掉以下空间,在HTML中,这在渲染时通常不是问题(因为通常不会渲染连续的空间),但去掉它仍然是个好主意。这还预先创建了一个regex表达式数组,看起来有点好。

听起来您可能需要使用一个小正则表达式

$oneBigDescription = preg_replace('/'sa's/', ' ', $oneBigDescription);

这将采用"Black a central"并返回"Black central"

您可以使用preg_replace仅替换"words on its own",如下所示:(我正在生成正则表达式,以便单词列表可以保持不变)

$wordsToReplace = ("a", "foo", "bar", "baz");
$regexs = array();
foreach ($wordsToReplace as $word) {
    $regexs[] = "/('s?)". $word . "'s?/";
}
$oneBigDescription = preg_replace($regexs, ''1', $oneBigDescription);