1

I am trying to explode a string using PHP but when only if the second instance of the delimiter is detected before exploding it, for my case i want to explode it after the second space is detected.

My String

Apple Green Yellow Four Seven Gray

My desire output

Apple Green
Yellow Four
Seven Gray

My initial code

$string = 'Apple Green Yellow Four Seven Gray';
$new = explode(' ',$string);

How can i achieve this using explode or any separating method with PHP? thanks in advance!

KaoriYui
  • 912
  • 1
  • 13
  • 43

4 Answers4

5

Nice question - it can be done in many way. i came up with this 1 -

 $data='Apple Green Yellow Blue';


$split = array_map(
    function($value) {
        return implode(' ', $value);
    },
    array_chunk(explode(' ', $data), 2)
);

var_dump($split);
Farsay
  • 312
  • 1
  • 9
2

You can use this also :

$string = 'Apple Green Yellow Four Seven Gray';
$lastPos = 0;
$flag = 0;
while (($lastPos = strpos($string, " ", $lastPos))!== false) {  
    if(($flag%2) == 1)
    {
        $string[$lastPos] = "@";
    }
    $positions[] = $lastPos;
    $lastPos = $lastPos + strlen(" ");
    $flag++;
}
$new = explode('@',$string);
print_r($new);
exit;
Mansi Raja
  • 152
  • 1
  • 13
1

You can use regular expression for that.

$founds = array();
$text='Apple Green Yellow Four Seven Gray';
preg_match('/^([^ ]+ +[^ ]+) +(.*)$/', $text, $founds);

Refer to the following answer too

Murtaza Khursheed Hussain
  • 15,176
  • 7
  • 58
  • 83
1

With the explode you can not get desired output. You have to use preg_match_all to find all values. Here is an example :

$matches = array();
preg_match_all('/([A-Za-z0-9\.]+(?: [A-Za-z0-9\.]+)?)/',
       'Apple Green Yellow Four Seven Gray',$matches);

print_r($matches);

Let me know if you have any issue.

Bhavin Solanki
  • 4,740
  • 3
  • 26
  • 46