php

PHP Explode Tutorial

PHP is one of the powerful website development tools that contains various built-in functions for various purposes. explode() method is one of the built-in PHP functions used to split string data into multiple parts based on any particular delimiter. This function returns an array after splitting the string or text data. Every part of the string can be easily retrieved by accessing the array value. Different use of explode() function are shown in this tutorial.

Syntax:

The syntax of the explode() function is given below.

explode(‘delimiter’,’string’,[limit])

Here, the first two parameters are mandatory, and the last parameter is optional. The searching string will be defined in the first parameter, and the main string which will be split will be defined in the second parameter. Any numeric value can be set as an optional parameter that will set the splitting limit. The value of the limit function can be positive or negative, or zero. The purposes of using different limit values have been explained in the following examples.

Example-1: Using empty string delimiter

In the following example, a single space has been used as delimiter which will split $mystr string into three words. Here, $parts is the array of three elements which contains the return values of explode() function. Create a PHP fie with the following script and run the script from the web server.

<?php

$mystr='I like Programming';

//space is used as delimiter
$parts=explode(' ', $mystr);

echo $parts[0] . '<br/>';
echo $parts[1] . '<br/>';
echo $parts[2];

?>

Output:

The following output will appear after executing the above script.

Example-2: Using a particular character as delimiter

Without space, any character or string can be used as delimiter. In the following code, ‘easy’ is used as delimiter. After using explode, the string will be divided into two parts and $parts array will contain two elements which will be printed later. Create a PHP fie with the following script and run the script from the web server.

<?php

$mystr='Learn programming with easy tutorials of linuxhint.com';

//’easy’ is used here as delimiter
$parts=explode('easy', $mystr);

//print the structure of the created array
print_r($parts);

echo '<br/>'. $parts[0] . '<br/>';

echo $parts[1];

 ?>

Output:

The following output will appear after executing the above script.

Example-3: Using the list() function to read the value of returning array

list is another built-in function of PHP that reads values of an array into variables. In the following example, ‘;’ is used as a delimiter, and the return values of explode function are retrieved by three variables named $a, $b, and $c using the list function. Create a PHP file with the following script and run the script from the webserver.

<?php

$mystr = 'hostname:localhost;username:root;password:abc123';

list($a,$b,$c)=explode(';',$mystr);

echo $a.'<br/>';
echo $b.'<br/>';
echo $c;

?>

Output:

The following output will appear after executing the above script.

Example-4: Using positive limit parameter

explode() function accepts a positive or negative number as the third parameter. Using a positive limit value in explode() function, the number of split values can be reduced. If you use the explode() function without limit, it will create an array of 6 elements. 5 has been used as the limit value in the following example. The last elements of the array will be created by combining the last two months. Create a PHP file with the following script and run the script from the webserver.

<?php

$mystr = 'January>February>March>April>May>June';

//Set positive value as limit
$output=explode('>',$mystr,5);

print_r($output);

echo '<br/>Last element of the array is: ' . $output[4] . '<br/>';

?>

Output:

The following output will appear after executing the above script.

Example-5: Using negative limit parameter

The negative value has been used as a limit in the following example. When you assign any negative value in a function, it counts from the last part of the string or array. For the value -2, the last 2 weekday names will not be added as array elements. Create a PHP file with the following script and run the script from the webserver.

<?php

$mystr = 'Saturday|Sunday|Monday|Tuesday|Wednesday|Thursday|Friday';

//set negative value as limit
$output=explode('|',$mystr,-2);

//Count total number of array elements
$length=count($output);

print_r($output);

echo '<br/>Total elements of the array is: ' . $length;

//Print the last element of the array
echo '<br/>Last element of the array is: ' . $output[$length-1] . '<br/>';

?>

Output:

The following output will appear after executing the above script.

Example-6: Split string based on multiple delimiters

The explode() function does not support multiple delimiters, but the string can be converted into an array based on multiple delimiters by using the str_replace() function with the explode() function. In the following example, an array has been created with the values used as delimiter values. Next, the str_replace() function has been used to replace the specific characters stored in the previously created array by the character, ‘#’. The explode() function was later used to split the string based on the character, ‘#’. Create a PHP file with the following script and run the script from the webserver.

<?php
//Define the text value
$text = "Course Code:CSE307, Course Name:Multimedia, Credit Hour:3.0, Department#CSE";

//Define an array of multiple delimeters
$delimiter_array = array(",",":","#");

//Replace all array values using '$' symbol
$replaced_str = str_replace($delimiter_array, '$', $text);

//Split the replaced string using explode
$output = explode('$', $replaced_str);

echo "<b>The splitted values of the string:<br/> </b>";

//Print the splitted value

echo $output[0]."-",$output[1]."<br/>";
echo $output[2]."-",$output[3]."<br/>";
echo $output[4]."-",$output[5]."<br/>";
echo $output[6]."-",$output[7]."<br/>";
?>

Output:

The following output will appear after executing the above script.

Example-7: Split string by removing whitespace

If the main string contains many whitespaces, then the explode() function will split the string with the whitespaces. This problem can be solved using the array_map() function with the explode() function. In the following example, the string data has been split using the explode() function without and with the array_map() function. Create a PHP file with the following script and run the script from the webserver.

<?php
//Define a string with many spaces
$text_with_space = "        PHP  ,  Python  ,  Java        ,  Bash,      JavaScript    ";

//Split the string without trim
$values_without_trim = explode(",",$text_with_space);

echo "<b>The splitted values before trimming:</b><br/><pre>";

//Print the splitted values
print_r($values_without_trim);

echo "</pre>";

//Split the string with trim
$values_with_trim = array_map('trim',explode(",",$text_with_space));

echo "<b>The splitted values after trimming:</b><br/><pre>";

//Print the splitted values
print_r($values_with_trim);

echo "</pre>";

?>

Output:

The following output will appear after executing the above script.

Example-8: Count the total number of words of a file

The total number of words in a file can be counted by using PHP script. The way of using explode() function to count the total number of words of a file has been shown in this example. The total number of words of a text file named clients.txt has been counted here. A counter variable has been used in the script to add the total numbers of words of each line of the file and finally find out the total number of words of the file. The fgets() function has been used here to read each file line. The explode() function has been used to split the content of each line into words based on colon (:) and the count() function has been used to count the total number of words.

The content of the clinets.txt file is given below.

clinets.txt

<strong>01</strong> : Md. Mossarof : Dhanmondi : [email protected]
<strong>02</strong> : Maruf Hossain : Mirpur : [email protected]
<strong>03</strong> : Rina Chowdhury : Jigatola : [email protected]
<strong>04</strong> : Tanzina Rahman : Malibagh : [email protected]

Create a PHP file with the following script and run the script from the webserver.

<?php
//Set an filename
$filename = 'clients.txt';

//Initialize the word counter
$word_counter = 0;

//Open the file for reading
$fh = fopen($filename, 'r');

//Check the file exist or not
if ($fh) {

  //Read the file line by line
  while (!feof($fh)) {

    //Read a line
    $line = fgets($fh);

    //Split the line based on clolon(;)
    $count = count(explode(':',$line));

    //Increment the counter
    $word_counter = $word_counter + $count;
  }
//Close the file
fclose($fh);
}

else
    echo "File does not exist.";

//Print the counter value
echo "There are $word_counter words in the $filename file.";

?>

Output:

The following output will appear after executing the above script. If the clients.txt file is divided based on the colon, then 20 words will be found that have been shown in the output.

Conclusion:

Different uses of explode() function have been shown in this tutorial to know the purposes of using this function in the PHP script. I hope the concept of the explode() function will be cleared after practicing the above examples properly. Another built-in function of PHP named implode is the opposite of the explode() function.  

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.