如何在PHP的正则表达式中允许撇号 [英] how to allow apostrophes in regular expressions in php

查看:123
本文介绍了如何在PHP的正则表达式中允许撇号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查字符串,该字符串应仅包含拉丁字母,破折号和撇号.长度必须为2-50.一切正常,但是如果字符串包含撇号,则函数返回false.

i want to check string, which should contain only latin letters, dashes and apostrophes.length must be 2-50. everything works, but if a string contains apostrophe, function returns false.

private function validName($name)
{
    if(!preg_match("/^[a-zA-Z\'\-]{2,50}$/", $name))
        return false;
    return true;
}

如何在我的正则表达式中加入撇号?我也尝试过这些

how to include apostrophe in my regex? i also tried these

preg_match("/^[a-zA-Z'-]{2,50}$/", $name)
preg_match("/^[a-zA-Z\'-]{2,50}$/", $name)
preg_match("/^[a-zA-Z'\-]{2,50}$/", $name)

但是无论如何它返回false

but it returns false anyway

更新:

在运行此方法之前,我用$name = htmlentities($name, ENT_QUOTES, "UTF-8");

Before run this method, i filter my string with $name = htmlentities($name, ENT_QUOTES, "UTF-8");

推荐答案

在检查字符串之前,请勿使用htmlentities,您可以在之后使用它.

You should not use htmlentities before checking your strings, you may use it after.

如果将$name = htmlentities($name, ENT_QUOTES, "UTF-8");应用于some'name,它将变为some'name.

If you apply $name = htmlentities($name, ENT_QUOTES, "UTF-8"); to some'name, it will turn into some'name.

此外,要缩短图案,请使用

Also, to shorten the pattern, use

preg_match("/^[A-Z'-]{2,50}$/i", $name)

/i不区分大小写的修饰符将使整个模式不区分大小写,而[A-Z]将匹配所有大小写的ASCII字母.

The /i case insensitive modifier will make the whole pattern case insensitive, and [A-Z] will match all upper- and lowercase ASCII letters.

这篇关于如何在PHP的正则表达式中允许撇号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆