I am upgrading an old PHP website and I have found several deprecated functions one of them is “split()” which I used many times in the past. Which functions we can use right now? And why is this massive used function deprecated?
Instead of “split()” function you can use “explode()” if you are not using regular expressions in the same way that “split()”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php // Example 1 $pizza = "piece1 piece2 piece3 piece4 piece5 piece6"; $pieces = explode(" ", $pizza); echo $pieces[0]; // piece1 echo $pieces[1]; // piece2 // Example 2 $data = "foo:*:1023:1000::/home/foo:/bin/sh"; list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data); echo $user; // foo echo $pass; // * ?> |
If you would need to use regular expressions you could use “preg_split()” function, as shown in the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php // split the phrase by any number of commas or space characters, // which include " ", \r, \t, \n and \f $keywords = preg_split("/[\s,]+/", "hypertext language, programming"); print_r($keywords); ?> Output: Array ( [0] => hypertext [1] => language [2] => programming ) |
All of the examples have been taken from the official webpage, please visit the official website for further information:
Manual for preg_split() function
Is brilliant to know that there is a great development behind PHP giving us upgrades and performance optimization, but why this function has been deprecated?
In the first case, using “explode()” we can found that it is substantially faster because it doesn’t split based on regular expression, so the string doesn’t have to be analyzed by the regex parser.
In the second case, using “preg_split()” has been deprecated in favor of the PCRE extension, which give us another question, is this the only function deprecated? And we found that “split()” function is member of a bunch of POSIX regex functions that they have also been deprecated and we can found them in the following document: