Reputation:
I have a problem with explode() function. I use the function to explode strings like "Name: Replica" but sometimes in the string has 2 or more colons ( ":" ) and there is the problem because my script is: Example: "Name: replica:replica2:replica3"
$explode = explode(":", $string);
$query = "INSERT INTO `table` (`field_1`, `field_2`) VALUES ('".$explode[0]."', '".$explode[1]."')";
And I need any solution for this problem. Because when I split the string after first colon ( ":" ) the second part must be the last part.
Upvotes: 3
Views: 2490
Reputation: 10981
edited as suggested by @Jon Nalley. Note that limit (3rd parameter) is only supported by PHP 5.x
list($attribute, $value) = explode(":", $string, 2);
Upvotes: 1
Reputation: 511
I think you want to use the 'limit' (third) argument to explode()
:
list($attribute, $value) = explode(":", $string, 2);
That will make sure you only get two results.
http://php.net/manual/en/function.explode.php
Upvotes: 6
Reputation: 36562
Use the optional third $limit
parameter to explode()
:
$explode = explode(":", $string, 2);
This tells explode()
to return an array with at most 2 elements, putting all subsequent colons into the second string fragment returned. Note, according to your examples you should be using a colon plus a space:
$explode = explode(": ", $string, 2);
But maybe that's just a coincidence.
Upvotes: 2