3

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.

Regards, George!

P.s. - Sorry for my English.

3 Answers3

6

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

deceze
  • 510,633
  • 85
  • 743
  • 889
Jon Nalley
  • 511
  • 2
  • 8
2

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.

David Harkness
  • 35,992
  • 10
  • 112
  • 134
1

edited as suggested by @Jon Nalley. Note that limit (3rd parameter) is only supported by PHP 5.x

list($attribute, $value) = explode(":", $string, 2);
yoda
  • 10,834
  • 19
  • 64
  • 92
  • I was try your method but abortively... This is my code: `$string = "Name: asdasd: asdasd:asdasdad"; list($attribute, $value) = explode(":", $string); echo $attribute.$value;` Try it and U'll see. –  Mar 01 '11 at 01:53