0

I have string

$argsInString = '"%s hello", \'%s world\', $foo->bar("anything", array(\'foo\' => 5 , \'bar\' => $a)),5, foo($s) ,$foo';

And I want convert to array like this:

$argsInArray = array('"%s hello"', '\'%s world\'', '$foo->bar("anything", array(\'foo\' => 5 , \'bar\' => $a))', '5', 'foo($s)', '$foo');

I try anything like this:

eval('$argsInArray = array(' . $argsInString . ');');

but this execute variables.

Could you help me how create $argsInArray from $argsInString?

EDIT: If it succeed to write a regular expression that would clothed individual parameters, using a single quote ('), in the string, then the eval work as described above.

Or could you write regular expression preg_match_all('...', $argsInString, $argsInArray); this is best.

4
  • 2
    Basically any time you're using eval in your code, you're doing something wrong. Where does $argsInString come from and what exactly are you going to be using the output for? Commented Feb 8, 2013 at 4:47
  • Yes, you have right with eval, i try write regular expression, but i faild. With eval i try use php compiler, but this faild too. $argsInString come from framework if translate template, this is defined variable. Commented Feb 8, 2013 at 4:52
  • Doesn't the framework have some sort of built-in parsing method for these strings? Commented Feb 8, 2013 at 4:55
  • Framework has not method for this. Commented Feb 8, 2013 at 6:47

1 Answer 1

1

Here's a Regex that will work on samples like this:

/(?: ?)([^,]*\(.*?\)|.+?)(?: ?)(?:,|$)/

Explained demo here: http://regex101.com/r/hK6nN0

Update:
to also match single and double quoted strings that contain , like:
"%s, hello", \'%s, world\', 5

/(?: ?)([^,]*\(.*?\)|[^,]*'[^']*'|[^,]*"[^"]*"|.+?)(?: ?)(?:,|$)/

Explained demo here: http://regex101.com/r/tD3cN9

1
  • Very very very nice, thank you. And I forgot one string $argsInString = '"%s, hello", \'%s, world\', $foo; like regex101.com/r/wF0xH8 Commented Feb 8, 2013 at 11:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.