Join my Laravel for REST API's course on Udemy 👀

PHP: Split strings based on a character

May 27, 2022  ‐ 2 min read

The way to split up a string on a certain character into an array of substrings is by means of the built-in PHP string function explode().

Consider the following example in which a URL path is split on a slash ('/') into multiple URL segments.

<?php

$path = 'blog/php/split-strings';
$segments = explode('/', $path);
print_r($segments);
//=> Array
//=> (
//=>     [0] => blog
//=>     [1] => php
//=>     [2] => split-strings
//=> )

The explode() function requires a delimiter string as a first argument and the string to split as its second argument.

explode(string $separator, string $string): array

It is not obligatory to use a single character as a separator, it is perfectly fine to split the string on https:// for example.

Potentially we can supply an optional third argument to explode() as well, this is the maximum amount of items we wish get returned in our array of results.

<?php

$path = 'blog/php/split-strings';
$segments = explode('/', $path, 2);
print_r($segments);
//=> Array
//=> (
//=>     [0] => blog
//=>     [1] => php/split-strings
//=> )

In contrary to exploding a string based on a character, we can also implode a string. This implodes an array of strings together into one string joined by a specified character.