How to split string by slash which is not between numbers?

Viewed 214

How to split string by slash which is not between numbers? I am using preg_split function below:

$splitted = preg_split('#[/\\\\\_\s]+#u', $string);

Input: "925/123 Black/Jack"

Splitted result now:

[
    0 => '925',
    1 => '123',
    2 => 'Black',
    3 => 'Jack'
]

Splitted result I want:

[
    0 => '925/123',
    1 => 'Black',
    2 => 'Jack'
]
3 Answers

One option is match 1 or more digits divided by a forward slash with whitespace boundaries on the left and on the right.

Then use SKIP FAIL, and match 1 or more times what is listed in the character class. Note that you don't have to escape the underscore.

(?<!\S)\d+(?:/\d+)+(?!\S)(*SKIP)(*F)|[/\\_\s]+

Explanation

  • (?<!\S)\d+(?:/\d+)+(?!\S) Match a repeated number of digits between forward slashes
  • (*SKIP)(*F) Skip
  • | Or
  • [/\\_\s]+ Match 1+ occurrences of any of the listed

Regex demo | Php demo

For example

$string = "925/123 Black/Jack";
$pattern = "#(?<!\S)\d+(?:/\d+)+(?!\S)(*SKIP)(*F)|[/\\\\_\s]+#u";
$splitted = preg_split($pattern, $string);
print_r($splitted);

Output

Array
(
    [0] => 925/123
    [1] => Black
    [2] => Jack
)

You may use

preg_split('#(?:[\s\\\\_]|(?<!\d)/(?!\d))+#u', '925/123 Black/Jack')

See the PHP demo and the regex demo and the regex graph:

enter image description here

Details

  • (?: - start of a non-capturing group:
    • [\s\\_] - a whitespace, \ or _
    • | - or
    • (?<!\d)/(?!\d) - a / not enclosed with digits
  • )+ - end of a non-capturing group, repeat 1 or more times.

Your regex is unnecessarily complicated. You need to split your string on:

  • either a space (maybe more generally - a sequence of white chars),
  • or a slash
    • not preceded by a digit (negative lookbehind),
    • not followed by a digit (negative lookahead).

So the regex you need (enclosed in # chars, with doubled backslashes) is:

#(?<!\\d)/(?!\\d)|\\s+#

Example of code:

$string = "925/123 Black/Jack";
$pattern = "#(?<!\\d)/(?!\\d)|\\s+#";
$splitted = preg_split($pattern, $string);
print_r($splitted);

prints just what you want:

Array
(
    [0] => 925/123
    [1] => Black
    [2] => Jack
)
Related