By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

PHP Preg_split Tutorial

how to use regular expressions with php preg_split to slice up your strings.

Edited: 2012-11-30 19:12

One of the most powerful ways to split a string in PHP, is trough the use of the preg_split function. This function allows you to provide a pattern that you want a string splitted by. The function creates a resulting array, which can then be worked with trough loops and other php functions.

The preg_split function can be used when you need to slice up complex strings, it takes a pattern and a source string as parameters. In this php tutorial, we will show how to use some simple regular expressions to split your strings with.

The below regular expression will only split the string by commas, regardless of any space before and after the comma, and with room for user errors.

$string = 'html,   html5   ,,, markup , search engines, website authority';
$keywords = preg_split("/[\s]*[,]+[\s]*/", $string);

Looping trough preg_split results

You can use a simple loop to work with the resulting array. Unless you know how many matches is present in the string, you would often count the results before looping trough the array. Knowing how to loop trough the resulting array, can be useful if you want to insert the results into a database.

$string = 'html,html5,markup,search engines,website authority';
$keywords = preg_split("/,/", $string);
$n = count($keywords); // Number of Pieces

$counter = 0;
while ($counter <= $n) {
  echo $keywords["$counter"] . '
'; ++$counter; }

See also

  1. Splitting with PHP Explode