...

/

Splitting Input Containing Substrings with the Delimiter

Splitting Input Containing Substrings with the Delimiter

Learn how to split inputs based on the delimiter.

Suppose we wanted to break the following string into an array on the , character:

one, two, three

We can accomplish this easily using the explode helper method like so:

Press + to interact
<?php
str('one, two, three')
->explode(',')->all();

This results in the following array:

array:3 [
  0 => "one"
  1 => " two"
  2 => " three"
]

The results are what we would expect given our sample input, but let’s say we want to split the following string:

one, "two, three", four, five

Into this array:

array:5 [
  0 => "one"
  1 => " two"
  2 => " "three, four, five""
  3 => " six"
  4 => " seven"
]

Using the explode method on this string produces the following results, which are not quite what we are after:

array:5 [
  0 => "one"
  1 => "
...