Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_split with two delimiters in PHP

How to merge two delimiters in preg_split? For example:

$str = "this is a test , and more";
$array = preg_split('/( |,)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($array);

will produce an array as

Array
(
    [0] => this
    [1] =>  
    [2] => is
    [3] =>  
    [4] => a
    [5] =>  
    [6] => test
    [7] =>  
    [8] => 
    [9] => ,
    [10] => 
    [11] =>  
    [12] => and
    [13] =>  
    [14] => more
)

but I want to get

Array
(
    [0] => this
    [1] =>  
    [2] => is
    [3] =>  
    [4] => a
    [5] =>  
    [6] => test
    [7] => ,
    [8] => and
    [9] =>  
    [10] => more
)

In fact, I want to merge the array elements when two delimiters are neighbors. In other words, ignoring the first delimiter if the next part is the second delimiter.

like image 771
Googlebot Avatar asked Dec 19 '12 00:12

Googlebot


People also ask

How Preg_match () and Preg_split () function works *?

How Preg_match () and Preg_split () function works *? preg_match – This function is used to match against a pattern in a string. It returns true if a match is found and false if no match is found. preg_split – This function is used to match against a pattern in a string and then splits the results into a numeric array.


1 Answers

Try using a character class: /[ ,]+/

The + is a quantifier meaning "1 or more"

like image 176
Niet the Dark Absol Avatar answered Oct 18 '22 16:10

Niet the Dark Absol