PHP 拆分为 preg_split() [英] PHP split to preg_split()
问题描述
我想把下面这个我一直在用的split函数转换成preg_split..有点混乱,因为值会不时变化...
I wanted to convert the following split function, which I have been using to preg_split.. it's a little confusing, because the value will change from time to time...
当前代码:
$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);
分割函数的输出:
Array ( [0] => D:/Projects/job.com/ [1] => /www/path/source )
推荐答案
preg_split() 类似于旧的 ereg-function split().您只需要将正则表达式括在 /.../
中,如下所示:
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);
这里的斜杠 /
实际上是正则表达式语法的一部分,不是在字符串中搜索的.如果 www
分隔符是可变的,您应该另外使用 preg_quote() 作为内部部分.
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.
但请注意,如果您只查找静态字符串,则不需要正则表达式.在这种情况下,您可以像以前使用 split() 一样使用 explode()
:
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);
这篇关于PHP 拆分为 preg_split()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!