CancelImage Upload

How to split up a string with regular expressions in PHP using preg_split()

Sometimes a string comes along that requires more than the traditional PHP split() function. Let us say for example we had multiple conditions by which a string needed to be split up by. In some instances a mere space would be enough, yet, the string should also be split up at each comma. Here then clearly a preg_split() is required:

<?php

$string = "New York Knicks, LA Lakers, Boston Celtics, Chicago Bulls";

$keywords = preg_split("/[\s,] /", $string);

echo implode($keywords, "<br>");

?>

The result of the above code will be each word listed out individually. No commas or spaces will remain thanks to the regular expression code specifying the split to take part on both:

preg_split("/[,] /", $string);

Now as soon as we only require the string to become split up at each comma, using a preg_split() would become overkill. As you will see the following two examples have exactly the same result.

A preg_split() on comma

<?php

$string = "New York Knicks, LA Lakers, Boston Celtics, Chicago Bulls";

$keywords = preg_split("/[,] /", $string);

echo implode($keywords, "<br>");

?>

A simple comma split():

<?php

$string = "New York Knicks, LA Lakers, Boston Celtics, Chicago Bulls";

$keywords = split(",", $string);

echo implode($keywords, "<br>");

?>

Clearly in this instance using the simple split() is the more elegant solution. However, knowing the difference between split() and preg_split() allows a better judgement of when which function is required.

Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com