2

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?

Lennart
  • 1,018
  • 1
  • 12
  • 27
  • 1
    [Works fine for me](https://eval.in/146970) – PeeHaa May 06 '14 at 07:17
  • I would not use regex special characters like the square brackets as delimiters. It only causes confusion. If you don't want the the slash, because you need to match, then use something like `~` or `#` (a special character, you don't need in your expression) – stema May 06 '14 at 07:50

3 Answers3

5

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

Community
  • 1
  • 1
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
2

/ 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);
Abhik Chakraborty
  • 44,654
  • 6
  • 52
  • 63
2

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);
merlin2011
  • 71,677
  • 44
  • 195
  • 329