What are alternative methods to using eval() in PHP when trying to parse and execute code from a string?

Using eval() in PHP to parse and execute code from a string can be risky as it opens up potential security vulnerabilities. To avoid this, you can use alternative methods such as creating a custom function or using built-in PHP functions like create_function() or anonymous functions (closures) to achieve the same result without the security risks.

// Using create_function() as an alternative to eval()
$code = 'echo "Hello, World!";';
$func = create_function('', $code);
$func();

// Using anonymous functions (closures) as an alternative to eval()
$code = 'echo "Hello, World!";';
$func = function() use ($code) {
    eval($code);
};
$func();