Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use preg_split() in php?

Tags:

php

preg-split

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?

like image 929
MD.MD Avatar asked Jun 12 '14 16:06

MD.MD


1 Answers

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.

like image 89
Majenko Avatar answered Oct 04 '22 16:10

Majenko