PHP explode (): this is how you use the function to separate strings

PHP command explode ()

The PHP programming language can do a lot of things with strings. A variant of this is covered by the PHP command "explode". As the name suggests, it "explodes" a character string into several pieces, which are then stored in an array by the command.

array explode (string $ delimiter, string $ string [, int $ limit])

The $ delimiter is the character based on which the string is divided. The variable $ limit can be inserted or omitted. If you enter a value (integer) there, you only get a limited number of elements in the array.

This is how the PHP command explode works - explanation and practical examples.

This is how the PHP command explode works - explanation and practical examples.

Code example with explode ()

The best way to explain the PHP commands is to program a few examples that show what comes out when you "get out".

Separate at spaces

Here is an example where a sentence is split at the spaces. Of course, all examples must be in the PHP markers be bordered.

$ string = "This is an example we share a sentence with."; $ array = explode ("", $ string); echo $ array [3];

The word "example" will appear as output, since the explode command separates the sentence using the spaces. Since an array always starts with 0 unless otherwise specified, $ array [0] is the word "That" and $ array [1] is "is" and $ array [3] is the word "example".

Separating a URL into individual components

Splitting a URL address into its various folders is a little more practical. In the example, a URL is split and then output as an array line by line.

$ url = "https://www.php.net/manual/de/function.explode.php"; $ separator = "/"; $ array = explode ($ separator, $ url); for ($ x = 0; $ x <count ($ array); $ x ++) {echo $ array [$ x]. " ";}

The output in this example is

https: www.php.net manual de function.explode.php

Separation of a list

So that you can see that the explode function in PHP can also handle two or more characters as "delimiters" or separators, I have an example here in which a list of fruits is exploded into an array, but with spaces and Are separated by commas.

If you were to choose the separator only from commas without spaces, you would have to execute a trim () on the individual array elements so that they do not have an appended space.

$ url = "apple, pear, orange, grapefruit, lemon, grape"; $ separator = ","; $ array = explode ($ separator, $ url); for ($ x = 0; $ x <count ($ array); $ x ++) {echo $ array [$ x]. " ";}

 

Output:

Apple pear orange tomato lemon grape
-
Did you like the article and did the instructions on the blog help you? Then I would be happy if you the blog via a Steady Membership or at Patreon would support.

Leave a Comment

Your e-mail address will not be published. Required fields are marked with * marked