【问题标题】:Using explode after using str_replace PHP使用 str_replace PHP 后使用爆炸
【发布时间】:2014-03-07 21:17:29
【问题描述】:

我有一个非常简单的代码,它替换字符串中的特定值,然后分解它。

但我需要在爆炸后对字符串进行计数,这是我的示例

$exclude=array();
$exclude[0]="with";
$exclude[1]="on";

$search_string="Boy with a t-shirt walking on the road";
echo str_word_count($search_string);  

//the str_replace is suppose to remove the word "with" and "on" from string
// count search string before explode

$sch2 = str_replace($exclude,"", trim($search_string));
$sch=explode(" ",trim($sch2));
echo count($sch);  


//count search string after explode

//The result of the second count after exploding is suppose to be 6 and NOT 8

但是当我计算爆炸后的 $sch 字符串时,它给了我 8

似乎有什么地方做错了,任何帮助将不胜感激。谢谢

【问题讨论】:

  • 试试var_dump($sch); - 也许 $sch 不包含您认为的内容?

标签: php str-replace explode


【解决方案1】:

如果您将 'with' 替换为空,那么您仍然有两个空格。所以拆分仍然会返回 8 个项目,其中一个是一个空字符串,其中单词“with”曾经是。

要解决这个问题,您可以替换 'with '(包括空格),因此您实际上也替换了两个空格之一。但我不知道这是否适用于您的实际生产代码,当然。

您也可以使用[array_filter][1] 过滤掉空值,如下所示:

$sch2 = str_replace($exclude,"", trim($search_string));
$sch = explode(" ",trim($sch2));
$sch = array_filter($sch);
echo count($sch);  

甚至:

// To prevent 'false positives' due to PHP's default weak comparison.
$sch = array_filter($sch, function($a){return $a !== '';});

【讨论】:

  • 很好——在 exclude 中的字符串中添加一个前导和尾随空格,然后用一个空格替换,会得到预期的结果。
  • 我想你的意思是其中两个是空字符串。
  • str_replace(" ", " ", str_replace($exclude,"", trim($search_string))) 用一个空格替换任何双空格。然后按原样继续。 @html-tosin
  • @Anonymous 啊,是的。 on 也被替换了,所以实际上你得到了两个由两个空格组成的序列,每个在展开的字符串中产生一个空字符串。
  • 我现在才用了var_dump,发现你说的很对
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-13
  • 1970-01-01
相关资源
最近更新 更多