【发布时间】:2012-03-10 05:07:48
【问题描述】:
在 JS 中我使用了这段代码:
if(string.match(/[^A-Za-z0-9]+/))
但我不知道,如何在 PHP 中做到这一点。
【问题讨论】:
在 JS 中我使用了这段代码:
if(string.match(/[^A-Za-z0-9]+/))
但我不知道,如何在 PHP 中做到这一点。
【问题讨论】:
以下代码将处理特殊字符和空格
$string = 'hi, how are you ?';
if (!preg_match('/[^A-Za-z0-9 #$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]+/', $string)) // '/[^a-z\d]/i' should also work.
{
echo 'english';
}else
{
echo 'non-english';
}
【讨论】:
if(preg_match('/^[A-Za-z0-9]+$/i', $string)){ // '/^[A-Z-a-z\d]+$/i' should work also
// $string constains both string and integer
}
胡萝卜放错了位置,所以它会搜索除方括号内的内容之外的所有内容。当胡萝卜在外面时,它会搜索方括号中的内容。
【讨论】:
if (preg_match('/^[\w\s?]+$/si', $string)) {
// input text is just English or Numeric or space
}
【讨论】:
\w 匹配所有带有变音符号的字符,例如 éèçàÀ...
PHP 可以像这样使用preg_match(regex, string) 将字符串与正则表达式进行比较:
if (!preg_match('/[^A-Za-z0-9]+/', $string)) {
// $string contains only English letters and digits
}
【讨论】:
看看这个快捷方式
if(!preg_match('/[^\W_ ] /',$string)) {
}
class [^\W_] 匹配任何字母或数字,但不匹配下划线。并注意! 符号。它将使您免于扫描整个用户输入。
【讨论】:
如果你需要检查它是否是英文的。您可以使用以下功能。可能会帮助某人..
function is_english($str)
{
if (strlen($str) != strlen(utf8_decode($str))) {
return false;
} else {
return true;
}
}
【讨论】:
使用preg_match()。
if (!preg_match('/[^A-Za-z0-9]/', $string)) // '/[^a-z\d]/i' should also work.
{
// string contains only english letters & digits
}
【讨论】:
if(ctype_alnum($string)) {
echo "String contains only letters and numbers.";
}
else {
echo "String doesn't contain only letters and numbers.";
}
【讨论】:
if(preg_match('/[^A-Za-z0-9]+/', $str)) {
// ...
}
【讨论】:
例如,您可以使用preg_match() 函数。
if (preg_match('/[^A-Za-z0-9]+/', $str))
{
// ok...
}
【讨论】: