10

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...

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 )
6
  • 1
    Why do you want to use preg_split? Commented Jan 19, 2011 at 12:34
  • is split just a function that uses preg_split ? and why don't you use explode ? Commented Jan 19, 2011 at 12:44
  • 1
    @RobertPitt: split() is an old, deprecated function that didn't use PCRE at all, but a different regex engine/syntax. Commented Jan 19, 2011 at 12:45
  • Ahh, I've just looked it up on PHP, never used such a function before. Commented Jan 19, 2011 at 12:46
  • i have function that build path, so i can easily use it in linux or windows or any platform, without worrying, about anything.. Commented Jan 19, 2011 at 12:46

1 Answer 1

21

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);
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for the answer. i cant accept it, because its giving me massage, that i can accept after 2 mins.. but it work, thanks
btw isnt preg_split is faster then explode?
@Basit: Not usually. Explode does a simple binary search, and doesn't have to look for complex/optional patterns. Also it's implemented as core PHP function, thus can deal with PHP strings better and generate a PHP array directly. The preg_split() function is slower because it makes a roundtrip over libPCRE. -- So explode() is always faster. (Regular expression matching with preg_match() OTOH can often be more efficient than simple PHP string function arithmetics.)
@Basit Just think of the work regex has to do compared to simply splitting a string by a particular keyword, it's obvious explode() should be faster!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.