Split A String By A Delimiter In PHP
Code snippet for how to Split A String By A Delimiter In PHP with sample and detail explanation
Splitting a string by a delimiter in PHP is a routine yet vital task in web development. This article aims to delve into the details of how you can do this through an easy-to-understand practical guide.
Code snippet to Split a String By a Delimiter In PHP
Here is a beneficial code snippet demonstrating how you can split a string by a specific delimiter in PHP:
<?php
$str = "The quick,brown,fox,jumps,over,the lazy,dog";
$delimiter = ",";
$array = explode($delimiter, $str);
print_r($array);
?>
Code Explanation for Splitting a String By a Delimiter In PHP
The snippet provided efficiently breaks down a string by a delimiter. Let’s understand how each part of the code functions.
In this example, we use the explode()
function. The explode()
function in PHP is used to split a string into an array by a string.
Our delimiter is a comma (,
), and the string we want to split is "The quick,brown,fox,jumps,over,the lazy,dog"
.
In the code, there is this line $array = explode($delimiter, $str);
where we call the explode()
function, giving it the delimiter and the string to split. The function returns an array, which we save into the $array
variable.
Finally, the print_r($array);
is used to print the elements of $array
, which will show all parts of the string, split by the provided delimiter. The ‘print_r’ function prints the array element with the numeric index as well as the element values.
After running the given code, we’ll get the following output:
Array
(
[0] => The quick
[1] => brown
[2] => fox
[3] => jumps
[4] => over
[5] => the lazy
[6] => dog
)
Following this step-by-step guide should help you understand how to split a string by a delimiter in PHP.