0

What is the best way to parse a string containing a function call with parameters in PHP so that I have the function name and the parameters with their correct types. Example:

$string = "ask('Do you want to continue?', ['yes', 'no'])";

I don't want to directly call that function, so eval is not an option. I want to do something based on the function name and use the parameters with their correct types. Is there an easy way in PHP?

I expect something like this as a result:

$name = 'ask';
$parameters = ['Do you want to continue?', ['yes', 'no']];
2
  • Nothing in PHP per se. You'd need to code that yourself. Have you tried anything so far?! Commented Feb 13, 2021 at 9:38
  • github.com/nikic/php-ast should be able to parse it to an AST. Commented Feb 13, 2021 at 9:41

2 Answers 2

1

Assuming that you want the arguments to be parsed to an array structure, you would still need to use eval (with all the precautions taken to ensure that the content is safe).

This code also assumes the format is as expected, i.e. it represents a valid function call, and the closing parenthesis is the final non-blank character:

$string = "ask('Do you want to continue?', ['yes', 'no'])";

$parts = array_map("trim", explode("(", substr(trim($string), 0, -1), 2));
$parts[1] = eval("return [$parts[1]];");

$parts will be:

[
    "ask",
    [
        "Do you want to continue?", 
        ["yes", "no"]
    ]
]
Sign up to request clarification or add additional context in comments.

Comments

0

I think you should use one good library to parse PHP code. that is some example of that kind of library

use PhpParser\Error;
use PhpParser\NodeDumper;
use PhpParser\ParserFactory;

$code = <<<'CODE'
<?php

function test($foo)
{
    var_dump($foo);
}
CODE;

$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
try {
    $ast = $parser->parse($code);
} catch (Error $error) {
    echo "Parse error: {$error->getMessage()}\n";
    return;
}

$dumper = new NodeDumper;
echo $dumper->dump($ast) . "\n";

https://github.com/nikic/PHP-Parser

1 Comment

Could you add how would you convert the $ast to the actual needed output.

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.