How can PHP developers ensure the security of their code when using eval() function?

When using the eval() function in PHP, developers should ensure that the input passed to eval() is sanitized and validated to prevent code injection attacks. One way to do this is by using a combination of regular expressions and input validation functions to filter out any potentially harmful code before passing it to eval(). Additionally, developers should avoid using eval() whenever possible and consider alternative methods to achieve the same functionality.

$input = $_POST['input'];

// Sanitize and validate input before passing it to eval()
if (preg_match('/^[a-zA-Z0-9\s\.\+\-\*\/\(\)]+$/', $input)) {
    eval($input);
} else {
    echo "Invalid input";
}