如何使用PHP在字符串中找到撇号


How to find apostrophe in string using PHP?

我无法检测到字符串中的撇号(')。我试着

if (strpos($username, chr(39)) > 0 )
if (strpos($username, ''') > 0 )
if (strpos($username, "'") !== FALSE)) 

没有运气。正确的做法是什么?

你列出了这个,它应该工作:

if (strpos($username, "'") !== FALSE)

单引号是一个特殊字符。因此,如果你想在单引号字符串中使用单引号,你必须用反斜杠'符号转义单引号。

int singleQuotePosition = strpos($username, '''');

int singleQuotePosition = strpos($username, "'");

PHP Manual: Strings

只是一个随机的猜测:也许你的单引号并不是真正的单引号。

如果是这样,您可能想尝试mb_strpospreg_match来查找该字符的UTF-8变体:

preg_match("/'/u", $string);

或者甚至用/'p{Pi}/u测试,看看它是否是另一种类型的单引号二重体。


另一个提示:如果您只是想测试字符是否存在,请尝试使用strstr,而不是strpos和布尔结果。