문제

How can I check a string in php for specific characters such as '#' or '\'?

I don't really want to use replace, just return true or false.

Thanks

도움이 되었습니까?

해결책

use the function strstr http://us2.php.net/manual/en/function.strstr.php Returns part of haystack string from the first occurrence of needle to the end of haystack

Note: If you only want to determine if a particular needle occurs within haystack , use the faster and less memory intensive function strpos() instead.

다른 팁

You can use the strpos function, if you only want to know if a string contains another one (the content of your questions seems to indicate that, even if your title says "remove").

Note : don't forget to use the !== or === operator, as the function can return 0 or false, and those have different meaning.


If you want to "remove" characters, str_replace or strtr might do the trick.

You can do something like this:

if (strpos($string, '#') !== false || strpos($string, '\') !== false) {
    // One of those two characters is in the string.
}

Note in particular the !== syntax, which differentiates between false (meaning the character isn't found) and 0 (meaning it was found at position 0).

Try regular expressions.

preg_match('/[#\\\\]/', $String);

Note: You have to escape backslashes '\' three times.

If you really want them in boolean format, you can use a ternary operator '?:' as such

preg_match('/[#\\\\]/', $String) ? true : false;

Or simply convert to boolean

(bool)preg_match('/[#\\\\]/', $String);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top