php – Convert string to array along with delimiter

Question:

I'm separating a string into an array if there is a certain preposition in it ('with', 'to', 'by'), but I want the return of that string also containing the delimiter, that is, the preposition.

Using preg_split and it explodes, I get the same 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
)

Answer:

Wouldn't it be something like that?

$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 there are any of the values ​​in the string and then when that value is found, the string is divided by spaces in order to separate the words into an array.

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

Scroll to Top
AllEscort