How can PHP syntax be executed from a string in a controlled manner?

When executing PHP syntax from a string, it is important to do so in a controlled manner to prevent security vulnerabilities such as code injection. One way to achieve this is by using the `eval()` function in PHP. However, it is crucial to sanitize and validate the input string before passing it to `eval()` to ensure that only safe and intended code is executed.

$input = "echo 'Hello, World!';";
$allowed_functions = array('echo', 'print'); // Define allowed functions

// Validate and sanitize input
if (preg_match('/^[a-zA-Z0-9\'";,()\s]+$/', $input)) {
    foreach ($allowed_functions as $function) {
        if (strpos($input, $function) !== false) {
            eval($input);
            break;
        }
    }
}