-->

php split to preg_split

2019-02-16 17:11发布

问题:

i wanted to convert following split function, which i been using to preg_split.. its little confusing, because the value will change time to time..

current code:
$root_dir = 'www';
$current_dir = 'D:/Projects/job.com/www/www/path/source';
$array =  split('www', 'D:/Projects/job.com/www/www/path/source', 2);
print_r($array);



output of the split function:
Array ( [0] => D:/Projects/job.com/ [1] => /www/path/source ) 

回答1:

preg_split() is similar to the old ereg-function split(). You only have to enclose the regex in /.../ like so:

preg_split('/www/', 'D:/Projects/job.com/www/www/path/source', 2);

The enclosing slashes / here are really part of the regular expression syntax, not searched for in the string. If the www delimiter is variable, you should additionally use preg_quote() for the inner part.

But note that you don't need regular expressions if you only look for static strings anyway. In such cases you can use explode() pretty much like you used split() before:

explode('www', 'D:/Projects/job.com/www/www/path/source', 2);