Search code examples
phpregexsplitpreg-split

How to match commas and "and" with preg_split in PHP


I have this string:

Rosemary J. Harris $^{1}$, Vladislav Popkov $^{2}$ and Gunter M. Sch\"utz $^{3,}$*

And I would liek to split it with commas (,) or "and" string.

So, the result should be:

[0] -> Rosemary J. Harris $^{1}$
[1] -> Vladislav Popkov $^{2}$
[2] -> Gunter M. Sch\"utz $^{3,}$*

I tryied this:

$splitAuthors = preg_split('/[, ]+[ and ]/', $authors);

Which is returning:

[0] -> Rosemary J. Harris $^{1}$
[1] -> Vladislav Popkov $^{2}$
[2] -> nd Gunter M. Sch\"utz $^{3,}$*

There is the "nd" in the last array item.

Thank you for your help.


Solution

  • Dont use character classes for this use the or seperator |

    This should give you the correct output:

    preg_split("/, | and /",$data)
    

    Gives the following output:

    Array
    (
        [0] => Rosemary J. Harris $^{1}$
        [1] => Vladislav Popkov $^{2}$
        [2] => Gunter M. Sch\"utz $^{3,}$*
    )