Question

I want to use preg_split to split a string on double forward slash (//) and question mark (?). I can use a single forward slash like this:

preg_split('[\/]', $string);

But

preg_split('[\//]', $string);
or
preg_split('[\/\/]', $string);

do not work.

How do you work with a double forward slash in an expression?

Was it helpful?

Solution

As you can see the string splits up at two forward slashes (//) and a question mark (?).

$str= 'Hi//Hello?New World/';
$splits = preg_split( '@(\/\/|\?)@', $str );
print_r($splits);

OUTPUT :

Array
(
    [0] => Hi
    [1] => Hello
    [2] => New World/
)

enter image description here

OTHER TIPS

/ and ? are reserved for the regex and you need to escape them when you use them literally.

$str = 'test1 // test2 // test3 ';

$array = preg_split("/\/\//", $str);
print_r($array);

For ? you can use as

$str = 'test1 ? test2 ? test3 ';

$array = preg_split("/\?/", $str);
print_r($array);

You can use a different delimiter for your regex.

<?php

$str = 'hello // world // goodbye ? foo ? bar';

$array = preg_split("!//!", $str);
print_r($array);
?>

For the question mark, you can use a character class to encapsulate it. You can do one OR the other using | to separate.

$array = preg_split("!//|[?]!", $str);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top