For a string, for example:
$string = " this is a string ";
What is the best approach for returning a csv array containing one number for each word that represents its first character position as follows:
$string = " this is a string "; ^ ^ ^ ^ 2 11 16 20
Ideally, the output would be just an array:
2,11,16,20
So far, here's what I have, but I think it's a little over my head, given my limited skills:
$string = " this is a string "; $string = rtrim($string); //just trim the right sides spaces $len = strlen($string); $is_prev_white = true; $result = ""; for( $i = 0; $i <= $len; $i++ ) { $char = substr( $string,$i,1); if(!preg_match("/\s/", $char) AND $prev_white){ $result .= $i.","; $prev_white = false; }else{ $prev_white = true; } } echo $result;
I get: 2,4,11,16,20,22,24,26
source share