Removing specific characters from a string in php

2019-08-05 16:34发布

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

标签: php char strpos
4条回答
可以哭但决不认输i
2楼-- · 2019-08-05 16:59

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.

查看更多
戒情不戒烟
3楼-- · 2019-08-05 17:02

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).

查看更多
闹够了就滚
4楼-- · 2019-08-05 17:03

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.

查看更多
贪生不怕死
5楼-- · 2019-08-05 17:07

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);
查看更多
登录 后发表回答