php - Pass a string as an argument -
i have string have grepped out of php file, arguments passed function, var_dump of string looks this
'foo bar', ['name' => 'john, smith'] and do, pass function 2 arguments. if there wasn't going chance of , in array explode string , pass 2 arguments function. can't , need parse string properly.
i can around calling eval.
eval("myfunction({$string});"); which work, using eval "risky". there native method pass string separate array of arguments pass function?
i can't run other php file, or change code of it, want grep out arguments (which have done) , pass these arguments own function.
edit:
so string greped changed, code need handle ways of writing php arguments (no spaces after ',', or ' or "). string , array, extracted text.
so need support things like;
"foo",['name' => 'john, smith'] "foo",[] "foo, bar", [1,2 ,3] sort of reverse var_export... var_import :)
so, seems best way might use eval... code "trusted" still feels dirty way it, , thought there method parse_str or parse_url.
edit 2:
so basically, twofiles. a.txt opened , regex grabs params in function. file b.php runs regex, , needs handle string pass different function.
a.txt can't changed php file. need run code. (eval works above).
file a.txt <?php ... ... $result = resetresult('foo bar', ['name' => 'john, smith']); .. ... ?> file b.php <?php $filecontents = file_get_contents('a.txt'); preg_match_all('/resultresult\((.*?)\)/', $filecontents, $matches); foreach($matches[1] $args) { // args = 'foo bar', ['name' => 'john, smith'] string. // need split args 'foo bar' can passed first argument, , array second argument.. somefunction($args[0], $args[1]); }
i did best, i'm still @ beginning php. there no official function convert "array string" array, tried workaround json_decode().
here code , fiddle
<? function get_string_between($string, $start, $end){ $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); } $original = "'foo, bar', ['name' => 'john, smith' , 'anotherkey' => 'another value']"; $str = get_string_between($original, "'", "'"); $arr = get_string_between($original, "[", "]"); $arr = json_decode(str_replace(' => ',':',str_replace('\'','"','{'.$arr.'}')), true); var_dump($str); print_r($arr); ?> output
string(8) "foo, bar" array ( [name] => john, smith [anotherkey] => value ) then call yourfunc($str,$arr).
of course code improved, it's start. there problem if array value contains =>, should fixed.
p.s.: get_string_between() taken here.
Comments
Post a Comment