Basic String Splitting

Learn and practice basic string-splitting techniques along with the implementation of a naive comment parser.

Overview

Accepting input strings and converting them into an array of data following some set of rules is a prevalent task when developing almost any type of application. Laravel and PHP provide many different helper methods and functions that help accomplish this, and some we have already seen, such as PHP’s mb_str_split function.

One of the most common tasks for doing this is to split a comma-separated string into an array of strings. In the code below, we can see a simple PHP program that separates some input text on the comma character:

Press + to interact
<?php
function splitString($value) {
return str($value)->explode(',')
->map(fn($x) => ltrim($x))
->all();
}
splitString('hello, world');

This produces the following list of strings:

array:2 [
  0 => "hello"
  1 => "world"
]

This particular example is relatively trivial to reason with and implement, but suppose our application’s requirements change, and we need to break the following string:

hello, "Hello, world", '"hello ", world!', world

Into the following array:

array:4 [
  0 => "hello"
  1 => "Hello, world"
  2 => ""hello ", world!"
  3 => "world"
]

Minor changes to our requirements like this can dramatically increase the complexity of our problem, and it might not be obvious where we should even start solving it. We will discuss these issues in this chapter; we’ll begin with more straightforward techniques and slowly increase the difficulty of the problems as we progress.

In the introduction of this chapter, We saw an example of one of the most basic ways we can split a string: using the explode helper method. There is not much else to add about this particular method compared to what we have discussed in previous sections. Still, we can explore some interesting use cases and address a common misconception.

We know that we can use the following to split by a single character: ...

Press + to interact
<?php
// Returns ["one", "two", "three"]
str('one, two, three')->explode(',')
->map(fn($x) => ltrim($x))
->all();

One point of confusion is how to split a string ...