Hello, I have a string that divide it into pieces with a comma. Each piece divide it into smaller interval with. You have to count how many pieces with interval there are in every piece with comma below. $string = "1str 1str, 2str 2str, 3str 3str"; $keywords = explode(',', $string); foreach ($keywords as $v) { $parts = explode(' ', $v); echo count($parts) . "<br>"; } Code (markup): Outputs the 2 3 3, not what it expect 2 2 2 Where is the problem? Why counting does not work properly? Thanks!
The problem is the 2nd time your telling it to split where there is a space. And you have a space before and after the words for the 2nd and 3rd set. try this and see. $string = "1str 1str,2str 2str,3str 3str"; $keywords = explode(',', $string); foreach ($keywords as $v) { $parts = explode(' ', $v); echo count($parts) . "<br>"; } PHP:
This will work: <?php $string = "1str 1str, 2str 2str, 3str 3str"; $keywords = explode(',', $string); foreach ($keywords as $v) { $parts = explode(' ', ltrim($v)); echo count($parts) . "<br>"; } ?> Code (markup): without changing the source
PHP - There is a function for everything. I pointed out why you were getting the wrong count but PopSiCLe gave you the solution that you want to use.
So perhaps even take it one step further ? $string = "1str 1str , 2str 2str , 3str 3str "; $keywords = explode(',', $string); foreach ($keywords as $v) { $parts = explode(' ', rtrim(ltrim($v))); echo count($parts) . "<br>"; } PHP:
Without having to worry about extra spaces/variables: foreach (explode(',', "1str 1str , 2str 2str , 3str 3str ") as $v) { echo str_word_count($v); } PHP:
The joke I've made for quite some time: PHP, yeah... there's a function for that. @KangBroke, I'm kind of laughing at the use of rtrim around ltrim... when there's just plain trim that does both ends at once! http://php.net/manual/en/function.trim.php
Use this for count all, $string = "1str 1str, 2str 2str, 3str 3str"; $keywords = explode(',', $string); foreach ($keywords as $v) { $parts = explode(' ', $v); $count+=count($parts); } echo $count; PHP: