PHP strpos check against many

你离开我真会死。 提交于 2019-12-02 19:11:42

问题


I am looking to use strpos to check for many chars in a string, for example:

I would like to separately check for the chars :,!, and & in $string. If any of them are found at any point, return false.

What's the most efficient way to do so? Thanks!


回答1:


Use preg_match

preg_match("/[:!&]/", $string) !== 1;

Example:

var_dump(preg_match("/[:!&]/", "this is !a test string"));
> int(1)
var_dump(preg_match("/[:!&]/", "this is a test string"));
> int(0)

preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.




回答2:


If any of them are found, return false.

Since you don't care about the actual position of the character, you could use regex:

preg_match("/[:!&]/", $str); // 1 if found, 0 if none found



回答3:


If your post is accurate and what you are trying to do is return FALSE if those strings are found, strpos() is not the right function. strpos() is to find where in a string certain characters (or strings) first appear.

If your stated goal is accurate, you probably want something more like this:

if( preg_match( "/[\:\!&]/", $str ) > 0 ) { return false; }


来源:https://stackoverflow.com/questions/14105699/php-strpos-check-against-many

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!