how to use preg_split() in php?

MD.MD picture MD.MD · Jun 12, 2014 · Viewed 49.2k times · Source

Can anybody explain to me how to use preg_split() function? I didn't understand the pattern parameter like this "/[\s,]+/".

for example:

I have this subject: is is. and I want the results to be:

array (
  0 => 'is',
  1 => 'is',
)

so it will ignore the space and the full-stop, how I can do that?

Answer

Majenko picture Majenko · Jun 12, 2014

preg means Pcre REGexp", which is kind of redundant, since the "PCRE" means "Perl Compatible Regexp".

Regexps are a nightmare to the beginner. I still don’t fully understand them and I’ve been working with them for years.

Basically the example you have there, broken down is:

"/[\s,]+/"

/ = start or end of pattern string
[ ... ] = grouping of characters
+ = one or more of the preceeding character or group
\s = Any whitespace character (space, tab).
, = the literal comma character

So you have a search pattern that is "split on any part of the string that is at least one whitespace character and/or one or more commas".

Other common characters are:

. = any single character
* = any number of the preceeding character or group
^ (at start of pattern) = The start of the string
$ (at end of pattern) = The end of the string
^ (inside [...]) = "NOT" the following character

For PHP there is good information in the official documentation.