$info = array( "https://segmentfault.com/q/1010000003711515", "http://www.baidu.com?admin.php&jasdhjas=asjd", 'php $a=0; echo "abc";', "假如这是第三个....*^%$#@!()[]{}", ); foreach ($info as $key => $value) { $message = "https://segmentfault.com/q/1010000003711515"; $preg = "/^".$value."$/"; if (preg_match($preg, $message)) { echo '匹配成功'; break; } }
Iterate through the $info array, add each string to it, and /^ turn it $/ into a regular expression, to match the provided $message , but because $info the string inside may have special characters, causing an error, so is there any way to $info escape each string?
Can it be escaped only at the $info time of definition?
Reply content:
$info = array( "https://segmentfault.com/q/1010000003711515", "http://www.baidu.com?admin.php&jasdhjas=asjd", 'php $a=0; echo "abc";', "假如这是第三个....*^%$#@!()[]{}", ); foreach ($info as $key => $value) { $message = "https://segmentfault.com/q/1010000003711515"; $preg = "/^".$value."$/"; if (preg_match($preg, $message)) { echo '匹配成功'; break; } }
Iterate through the $info array, add each string to it, and /^ turn it $/ into a regular expression, to match the provided $message , but because $info the string inside may have special characters, causing an error, so is there any way to $info escape each string?
Can it be escaped only at the $info time of definition?
/There is a special meaning in the regular expression, so the subsequent '/' will go wrong, you need to precede the backslash with a backslash to \ cancel the escape.
Defines the $preg, but uses the $info, which is a mistake
And there's the regular wildcard character that's going to be \ escaped,
Your example above should be changed to
$preg = "/^https:\/\/segmentfault\.com\/q\/1010000003711515$/"; $test = "https://segmentfault.com/q/1010000003711515"; preg_match($preg, $test);
I think you just say what you want to do better, feel that you are wrong.
$preg is an unknown variable.
You're too big a premise.
If these expressions are programmer input, then it is the programmer's problem.
If these expressions are user-input, then the user should be informed of the regular expression in the input interface, let himself notice.
You can use JS to escape the special character of the regular expression, but it can cause 2 escapes (such as the user would have entered the escaped content http:|b4831e42daf1db770cdbc01d41578e020|/.+)
Example
document.getElementById('test').value = (new RegExp(document.getElementById('test').value)).toString();
In addition, you may also have problems with forcing the addition of/^ and $/in your program.