Splitting strings in PHP using explode Vs split functions
Aditya January 16th
Splitting strings into an array is nothing new and is pretty easy using the explode function if your input string pattern is consistent. But if your input string pattern is a little less consistent, then using the split function makes it a lot easier than doing some post-processing on array elements produced by the explode function.
Here is an example:
I have an input field where I ask user to enter her friends’ email addresses to invite them. I instruct user to use commas to separate multiple email addresses. But user will not necessarily enter all email addresses with consistent pattern. The input string may not contain any spaces, or may contain optional spaces before or after actual email addresses. For example:
$recipient_email_list = "abc@example.com, def@example.com,ghi@example.com , jkl@example.com , mno@example.com";
$recipient_emails = explode(',', $recipient_email_list);
//Echo with '|' delimiter to see the spaces before and after email address:
foreach ($recipient_emails as $recipient_email)
{
echo $recipient_email.'|';
}
The output is as below:
abc@example.com| def@example.com|ghi@example.com | jkl@example.com | mno@example.com|
In above example, few exploded strings have additional spaces. So you need to do post-processing on the exploded array as below:
$i=0;
foreach ($recipient_emails as $recipient_email)
{
$found = preg_match('/ /', $recipient_email);
if($found)
{
$recipient_emails[$i]= trim($recipient_email);
}
$i++;
}
foreach ($recipient_emails as $recipient_email)
{
echo $recipient_email.'|';
}
Then the output is as below:
abc@example.com|def@example.com|ghi@example.com|jkl@example.com|mno@example.com|
But there is another easy way to avoid this extra lines of post-processing code. Use split function as below:
$recipient_emails = split(' *, *', $recipient_email_list);
foreach ($recipient_emails as $recipient_email)
{
echo $recipient_email.'|';
}
Then the output is as below:
abc@example.com|def@example.com|ghi@example.com|jkl@example.com|mno@example.com|
In above example, split function actually splits an input string into an array by regular expression ‘ *, *’ i.e. split by zero or more spaces after or before the comma character.
I hope you will find this useful. If you have more inputs or questions, then please share in comments section.
your post really helps, thanks for posting!
Outsourcing Philippines
28 Mar 09 at 10:22 pm