Possible Duplicate:
preg_match php special characters
As part of my register system I need to check for the existence 开发者_如何学Pythonof special characters In an variable. How can I perform this check? The person who gives the most precise answer gets best.
Assuming that you mean html entities when you say "special chars", you can use this:
<?php
$table = get_html_translation_table(HTML_ENTITIES, ENT_COMPAT, 'UTF-8');
$chars = implode('', array_keys($table));
if (preg_match("/[{$chars}]+/", $string) === 1) {
// special chars in string
}
get_html_translation_table
gets all the possible html entities. If you only want the entities that the function htmlspecialchars
converts, then you can pass HTML_SPECIALCHARS
instead of HTML_ENTITIES
. The return value of get_html_translation_table
is an array of (html entity, escaped entity) pairs.
Next, we want to put all the html entities in a regular expression like [&"']+
, which will match any substring containing one of the characters inside square brackets of length 1 or more. So we use array_keys
to get the keys of the translation table (the unencoded html entities), and implode them together into a single string.
Then we put them into the regular expression and use preg_match
to see if the string contains any of those characters. You can read more about regular expression syntax at the PHP docs.
$special_chars = // all the special characters you want to check for
$string = // the string you want to check for
if (preg_match('/'.$special_chars.'/', $string))
{
// special characters exist in the string.
}
Check the manual of preg_match for more details
A quick google search for "php special characters" brings up some good info:
htmlentities() - http://php.net/manual/en/function.htmlentities.php
htmlspecialchars() - http://php.net/manual/en/function.htmlspecialchars.php
精彩评论