Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string with multiple delimiters

Tags:

regex

replace

php

I have seen many (before you go flagging this as a duplicate) on how to do this, but for some reason my output isn't working:

// $delimiters wanted: ', ' | '; ' | ',' | ';' | ' , ' | ', and ' | ' and ' | ',and '
$str = 'Name 1, Name 2; Name 3;Name4 , Name 5,Name 6, and Name 7,and Name 8 and Name 9';
$delimiter = array(
    ', ',
    '; ',
    ';',
    ',',
    ' , ',
    ', and ',
    ' and ',
    ',and '
);
$str_new = explode( $delimiter[0], str_replace($delimiter, $delimiter[0], $str) );

However, when I output the array, I get this:

<?php foreach($str_new as $new) { echo 'a' . $new; } ?>

Array (
    [0] => Name 1
    [1] => Name 2
    [2] => Name 3
    [3] =>        // WHY IS THIS EMPTY?
    [4] => Name 4
    ...
)

So is there a better way to match the delimiters I have listed?

like image 831
markb Avatar asked Feb 15 '26 19:02

markb


1 Answers

I'd use regexp like this in your case:

preg_split('/,? ?and | ?[,;] ?/', $str)

You may also want to replace spaces by \s if the other space characters may appear (like TAB, for example) or even \s* instead of ? to cover the case of multiple spaces.

like image 194
Alexey Avatar answered Feb 19 '26 09:02

Alexey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!