2

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'
]
Jackson
  • 23
  • 3
  • 1
    Would lookarounds be available for you? If so, maybe use lookbehind and lookahead? – JvdV Apr 10 '20 at 10:11

3 Answers3

1

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
)
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
1

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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

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
)
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41