Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_split regex does not split with dot

I'm using the following regex to split a string to an array. Everything goes fine but for some reason it does not the splitting with \.(space). How would i need to change it to make it work?

  $sentences  = preg_split(" / (\. |, and|, or|, but|, nor|, so|, for|, yet|after|although|as|as if|as long as|because|before|even if|even though|if|once|provided|since|so that|that|though|till|unless|until|what|when|whenever|wherever|whether|while) /",$sentences); 
like image 841
bicycle Avatar asked Jan 28 '26 07:01

bicycle


2 Answers

Your whitespace is the issue here. Regular expressions take this into account, so change it to this:

$sentences = preg_split("/(\. |, and|, or|, but|, nor|, so|, for|, yet|after|although|as|as if|as long as|because|before|even if|even though|if|once|provided|since|so that|that|though|till|unless|until|what|when|whenever|wherever|whether|while)/",$sentences); 

Note how the whitespace after the first / and before the final / have been removed.

like image 88
Jon Cairns Avatar answered Jan 30 '26 21:01

Jon Cairns


Since you're using double quotes, you have to double escape the dot, so \\. instead of just \.

like image 37
ulentini Avatar answered Jan 30 '26 20:01

ulentini