开发者

Why is this preg_split not working as I want it to?

开发者 https://www.devze.com 2023-04-12 21:00 出处:网络
I have a preg_split pattern as below: $pattern = \'/[, ;:-_.|+#\\/]/\'; I use $pcs = preg_split($pattern, $string);

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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号