Click to See Complete Forum and Search --> : Spliting a string into array
diamonds
10-05-2003, 12:20 PM
php.net (http://www.php.net)'s documentation for explode, split, and other functions is a little, well, wierd.
Can someone point me in the right direction?
I am looking for a script that will split a string into an array.
<?php
$variable = '12/34/2000';
$variable = explode('/',$variable,3);
echo $variable[0];//somthing like "12"
?>
For some reason, I get an error with explode() AND split():
Notice: Undefined offset: 1 in .../script.php on line 148
fyrestrtr
10-05-2003, 01:14 PM
Your problem is that when you are setting the optional limit, it is too big for the array.
For an input like 01/10/2000
[0] = 01
[1] = 10
[2] = 2000
As you can see, there is no element at index [3].
You don't need to set the limit, instead, you can do this :
$var = "00/00/0000";
$parts = explode("/",$var);
echo "<pre>"; print_r($parts); echo"</pre>";
This will show you what the array is that is being returned. From there, you can pick out the index of the element you want.
diamonds
10-05-2003, 04:09 PM
That dosen't seem to be the problem...
<?php
$q = "value1>value2";
$tmp_arr_1 = split(">",$q,1);
$program = $tmp_arr_1[0];
echo $tmp_arr_1[0];
?>
returns:
"value1>value2"
and there is no value
$tmp_arr_1[1].
and it dosen't matter if I change it to $tmp_arr_1 = split(">",$q);, removing the ",1" from the near-end of the function
diamonds
10-05-2003, 04:17 PM
It does help, removing the limit area.
But, how do I make it split only at the first separator, and never again? without an error?
diamonds
10-05-2003, 05:11 PM
By doing somthing like this, I can control the errors:
if(substr_count(var,'/')<=2){
$var2 = explode('/',$var);
}else{
$var2 = explode('/',$var,1);
}
thanks :)
fyrestrtr
10-06-2003, 03:50 AM
If you just want to split it at one character, then you don't need split() or explode(). You can do it with a combination of string functions.
Say you wanted everything to the right of a certain character. You can then use strstr (http://www.php.net/strstr), which will return everything from a certain needle (or search point), till the end of the string. The returned string will include the needle.
Example (from the manual) :
$email = 'user@example.com';
$domain = strstr($email, '@');
print $domain; // prints @example.com
If you want to return everything to the left of a string (everything leading up to the needle), then you can use a combination of substr (http://www.php.net/substr) and strpos (http://www.php.net/strpos).
Example :
$haystack = "10/10/1000";
$needle = "/";
echo substr($haystack,0,strpos($haystack,$needle)+1);
Hope this helps.