2

I want to split a string in PHP into a 'name' part (string) and a 'keys' part (array of integers).

Example input:

 $input = "Sum(1, 5, 7)";

Desired output:

 $name = "Sum";
 $keys = [1, 5, 7];

I've been looking at explode, str_split preg_split, and I'm sure there are many possible implementations. What's the most elegant solution?

6
  • Euh, what about Sum(1, Sum(1, 5, 7), 7) ? What's the expected output ? Commented Feb 21, 2014 at 13:30
  • Is it always in the format "word" "bracket" "comma delimited numbers" "bracket"? Commented Feb 21, 2014 at 13:31
  • @Grim, Great questions. Yes I would expect it always to be "word" "bracket" "comma delimited numbers" "bracket". HamZa's example would be an invalid (illegal) input. The string is in a config file so I have control regarding unexpected inputs. Commented Feb 21, 2014 at 13:34
  • @MMacdonald Is the input Sum(1, 5, 7) or could there be several "parts" like Sum(1, 5, 7) , Div(10, 5), Mul(3, 4) ? Commented Feb 21, 2014 at 13:57
  • @HamZa - exclusively Sum(1, 5, 7) ... word, bracket, comma delimited numbers, bracket. No other variations. Commented Feb 21, 2014 at 14:34

2 Answers 2

6
$input = "Sum(1, 5, 7)";

preg_match_all('#(\w+)\((.*?)\)#', $input, $m);

print_r($m);

Example Ideone.com

Sign up to request clarification or add additional context in comments.

2 Comments

seems like a good start but this actually returns '1, 5, 7' as string, not as an array.
from there, just explode the string in to an array.
1

Try this out:

$input = "Sum(1, 5, 7)";

$split1=explode('(',$input);

$name=$split1[0];
echo $name;
$newk=rtrim($split1[1],')');
echo '<br>';
$keys=explode(',',$newk);
print_r($keys)

Online demo

1 Comment

Please put the code in the answer as well so the answer isn't purely a link.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.