PHP » Strings » preg_split()

Syntax:
array preg_split(string separator, string s [, int n [, int flags]])
separator
Pattern that separates the elements.
s
String to convert to an array.
limit
Maximum number of elements to return in the array.
flags
Modifies the behavior of preg_split().

Makes an array of a string.

This function is similar to explode(), but uses Perl regular expressions instead of just strings for the separator. The string is split where there is a match for the separator, and the portions of the string between the matches are returned as elements of an array. If the n parameter is provided, a maximum of n elements will be returned in the array. The flags that can be specified are PREG_SPLIT_NO_EMPTY, for no empty strings in the returned array, PREG_SPLIT_DELIM_CAPTURE, which makes preg_split() return the subpatterns within parentheses, and PREG_SPLIT_OFFSET_CAPTURE, which makes the function return the offsets of the matches.

Examples

Code:
<pre>
<?php

$s = "http://www.somedomain.com";
$pattern = "/[http:\/\/|\.]/";

$a = preg_split($pattern, $s, 0,
   PREG_SPLIT_NO_EMPTY | PREG_SPLIT_OFFSET_CAPTURE);
print_r($a);

?>
</pre>
Output:
Array
(
   [0] => Array
       (
           [0] => www
           [1] => 7
       )

   [1] => Array
       (
           [0] => somedomain
           [1] => 11
       )

   [2] => Array
       (
           [0] => com
           [1] => 22
       )

)

Explanation:

preg_split() is used to separate the components of a host name in a URL.

See Also: