Sunday, December 15, 2024
HomeWeb application programmingPHP programmingPHP: Break Apart Strings with explode

PHP: Break Apart Strings with explode

PHP has a built-in function knows as explode which breaks apart a string using substring separators. This tech-recipe describes the use of the explode() function.


The explode function breaks a string into an array of strings using another string as a separator. For example, consider the following string:

$bigstr='user:password:uid:gid'

It can be broken into an array of strings by the colon character using the following command:

$strs = explode(':',$bigstr);

In this case, $strs[0] will contain ‘user,’ $strs[1] will be ‘password’ and so on.

The explode function has an optional limit parameter which greatly increases it flexibility. When this value is positive, the function will return that many array elements with the last array element containing all of the remaining fields. For example, given an input string that contains a keyword, a number, and a path all separated by a space, the path can contain spaces and would be difficult to extract. A postive limit value of 3 will chop this string perfectly:

$line = 'data 7 C:\Documents and Settings\file.doc';
$parts=explode(' ',$line,3);
echo $parts[0];
data
echo $parts[2];
C:\Documents and Settings\file.doc

If the limit value is negative, explode will provide that many array elements and the last element will contain only one field. In the example above, there would be three elements in the parts array and the third element would be “C:\Documents”

David Kirk
David Kirk
David Kirk is one of the original founders of tech-recipes and is currently serving as editor-in-chief. Not only has he been crafting tutorials for over ten years, but in his other life he also enjoys taking care of critically ill patients as an ICU physician.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

LATEST REVIEWS

Recent Comments

error: Content is protected !!