Removing specific characters from a string in php

我的未来我决定 提交于 2019-12-11 10:56:16

问题


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


回答1:


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.




回答2:


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:


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:


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


来源:https://stackoverflow.com/questions/1388966/removing-specific-characters-from-a-string-in-php

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