Log in

View Full Version : Splitting strings



keyboard
07-26-2012, 03:03 AM
Hello everyone,
I'm trying to split one string into several, but not sure how...

Lets say I have a string variable


$var = 'test@gmail.com~|~test@hotmail.com~|~test@grapevine.com';

How would I split that into three different strings... eg.


$var1 = 'test@gmail.com';
$var2 = 'test@hotmail.com';
$var3 = 'test@grapevine.com';

~|~ is the divider I want to use....
Any help?

jscheuer1
07-26-2012, 04:12 AM
It's easier to just explode it and use the resulting array:


<?php
$var = 'test@gmail.com~|~test@hotmail.com~|~test@grapevine.com';
$vars = explode('~|~', $var);
echo implode('<br>', $vars);
?>

But if you need individual variables, you could do a foreach on the array to make them:


<?php
$var = 'test@gmail.com~|~test@hotmail.com~|~test@grapevine.com';
$vars = explode('~|~', $var);
foreach($vars as $key => $val){
$k = $key + 1;
$GLOBALS["var$k"] = $val;
}
echo $var1 . '<br>';
echo $var2 . '<br>';
echo $var3 . '<br>';
?>