function legalChars($str) { // Define allowed characters $allowed = "/^[a-zA-Z0-9_\-\s\.\,\!\#\$\%\&\'\*\+\:\/\=\?\@\[\]\^\_\`\{\|\}\~\(\)]+$/"; // Check if string matches allowed characters if(preg_match($allowed, $str)) { return true; } else { return false; } }
function legalChars($str, $allowedChars) { // Check if string contains only allowed characters return preg_match('/^[' . $allowedChars . ']+$/', $str); }Example 2: This code example defines a PHP function called "legalChars" that checks if a string only contains the characters specified in the second argument. This allows the caller to define what is considered "legal" for their purposes. The function uses "preg_match" to continue validation. Package Library: The package library that can be utilized with this function is "PHP regular expression".