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
.
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 i开发者_如何学JAVAn 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
Try
$pcs = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY);
Read more in the manual: http://php.net/manual/en/function.preg-split.php
Look at your whitespace. I am going to assume the following:
- "Hello how are you" split results has
$pcs[0] == ''
- "Hello how are you " split results has
$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.
精彩评论