如何计算逗号之间的“单字”子串

时间:2012-02-17 20:38:46

标签: php

我有这个字符串:

$array= 'orange, fruit, apple juice'

我想计算字符串中的单字子串(橙色/水果)

我试过了

//Explode string at commas
$explode_tags = explode(",", $array);

//Check if space exists in substrings
foreach ($explode_tags as $explode_tag) {
  if (strstr(trim($explode_tag), ' ') == false) { 
  ...
  }
}   

现在我无法弄清楚只有当上面的IF语句出错时如何计算子串。

2 个答案:

答案 0 :(得分:2)

试试这个:

$num = count(array_filter(explode(",",$array),function($a) {return !strpos(trim($a)," ")}));

使用:countarray_filterexplodestrpostrim

答案 1 :(得分:1)

怎么样:

//Explode string at commas
$explode_tags = explode(",", $array);

$count = 0;
//Check if space exists in substrings
foreach ($explode_tags as $explode_tag) {
      if (strpos(trim($explode_tag), ' ') == false) { //strpos better for checking existance
          $count++;
      }
}

//Do something with $count