如果没有反斜杠,则仅在前向斜杠上使用PHP分割字符串

I am making a parser for my SlashCategory, which requires me to split (or tokenize) each string based on the / character. I am using PHP's explode() function, which works well. For example, it takes the following:

Book/Title/Lord Of The Flies/Author/William Golding

And creates an array with:

[0] Book
[1] Title
[2] Lord Of The Flies
[3] Author
[4] William Golding

However, I have a problem. I do not want explode() to break up the string if the forward slash is preceded by a backslash. For example:

Url/Google/http:\/\/www.google.com

I want to have an array containing:

[0] Url
[1] Google
[2] http://www.google.com

Not:

[0] Url
[1] Google
[2] http:
[3] 
[4] www.google.com

How can I do this?

Use preg_split (see http://php.net/manual/en/function.preg-split.php). Example:

$input = 'Url/Google/http:\/\/www.google.com';
$output = preg_split('|(?<!\\\)/|', $input); //Yes, thats 3 times a backslash

Now, the data in $output will still contain your escaped slashes, you'll need to unescape them, like this:

$output = preg_split('|(?<!\\\)/|', $input);
array_walk(
    $output,
    function(&$item){
        $item = str_replace('\\/', '/', $item);
    }
);

Ha, I know this has its faults but a one liner could be something like this:

<?php
    $s = "Url/Google/http:\/\/www.google.com";
    var_dump (explode('#####',str_replace('\\#####','/',str_replace('/','#####',$s))));
?>

Though you would have to find a practical something other than '#####' as you might have a string like that that you may parse.