Convert string into array along with delimiter

Asked

Viewed 241 times

3

I am separating a string in array if there is a certain preposition in it ('com', 'for', 'por'), but I want the return of this string also containing the delimiter, ie the preposition.

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

$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 seek:

Array
(
    [0] => Programação 
    [1] => com
    [2] =>  Stackoverflow
)
  • You want when it contains com, "burst" the string? You wouldn’t have to check the word first com|para|by|por with preg_match?

  • Yes, @Wallacemaxters. And I need the preposition next to the result.

2 answers

1

Wouldn’t that be something?

$regex = 'Filme com pipoca';

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

Upshot:

['Film', 'com', 'Popcorn'']

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

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

  • However, if you have something else in the word, it also returns as a key in the array. Ex: 'Stackoverflow by Wallace Maxter' it returns: ['Stackoverflow', 'por', 'Wallace', 'Maxter'] when it should just be: '[Stackoverflow', 'por', 'Wallace Maxter']

  • I get it. You want por enter the division processing of the regular expression and at the same time want it to "continue" in the array.

  • 1

    That’s right, @Wallace. I will receive a string and separate it into 3 parts, I got it as follows: preg_split('/(with|to|by|by)/', $string, false, PREG_SPLIT_DELIM_CAPTURE );

  • Cool. Now I understand what this guy’s for Delim Capture

  • I’ll add on the answer :)

  • Didn’t add, @Wallace.

Show 1 more comment

0


preg_split('/(com|para|by|por)/', $string, false, PREG_SPLIT_DELIM_CAPTURE );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.