I have a preg_split pattern as below:
$pattern = '/[, ;:-_.|+#\/]/';
I use
$pcs = preg_split($pattern, $string);
if string is ” Hello how are you”, then count($pcs) == 5.
if string is “Hello how are you”, then count($pcs) == 4.
if string is ” Hello how are you “, then count($pcs) == 6.
Does anybody know what the problem is? (I want it to return 4 in all above cases).
My plan is to split a user-inputted string into words simply.
The string entered may contain the characters in the pattern above.
Thanks
Look at your whitespace. I am going to assume the following:
$pcs[0] == ''$pcs[0] == ''and$pcs[5] == ''Since there is white space at the beginning and/or end (depending on the case) your preg_split is going to still create the split between nothing and the first and/or last word. If you want to avoid this you should run a trim() first before your split.