Saturday 28 December 2013

Split string into array using regular expression in PHP

Today, i came across a handy PHP function which will convert the string in to array based on regular expression. i.e preg_split().

Implementation:
$test = "Hi, my blog name sureshdotariya";

$result = preg_split('/[\s,]+/',$test,-1,PREG_SPLIT_NO_EMPTY);
Above code will display the below output
array(5) {
  [0]=>
  string(2) "Hi"
  [1]=>
  string(2) "my"
  [2]=>
  string(4) "blog"
  [3]=>
  string(4) "name"
  [4]=>
  string(14) "sureshdotariya"
}

Explanation:

Here the String will be splitted based on comma (,) and space and the output will be an array. This method will accept 'regular expression' as first parameter, followed by String as second parameter. Third parameter is the limit for applying conversion  and finally FLAG as the fourth parameter.

For more detailed information about its method usage, arguments and other features, please refer the official documentation.

Hope, you enjoyed this Post.

No comments:

Post a Comment