Convert string to array along with delimiter

3

I am separating a string in array if there is a certain preposition in it ('with', 'to', 'by'), but I want to return the string containing the delimiter as well, ie the preposition. >

Using preg_split and explode, I have the same and unsatisfactory result:

$string = 'Programação com Stackoverflow';

$resultado = explode('com', $string);
$resultado2 = preg_split('/com|para|by|por/', $string);

Array
(
    [0] => Programação 
    [1] =>  Stackoverflow
)

The expected result for what I'm looking for:

Array
(
    [0] => Programação 
    [1] => com
    [2] =>  Stackoverflow
)
    
asked by anonymous 08.09.2015 / 16:55

2 answers

0
preg_split('/(com|para|by|por)/', $string, false, PREG_SPLIT_DELIM_CAPTURE );
    
14.09.2015 / 19:34
1

Would not it be something like this?

$regex = 'Filme com pipoca';

if (preg_match('/com|by|para|por/u', $string)) {
    $array = preg_split('/\s+/u', $string, -1, PREG_SPLIT_NO_EMPTY);
}

Result:

  

['Movie', 'with', 'Popcorn']

We use an expression to check if any of the values exist in the string, and then when this value is found, the string is divided by the spaces in order to separate the words into an array.

I think it's a good idea to use PREG_SPLIT_NO_EMPTY , to return no empty value.

    
08.09.2015 / 17:19