从PHP中的字符串中删除特定字符

发布于 2024-08-04 05:56:40 字数 86 浏览 3 评论 0原文

如何在 php 中检查字符串中的特定字符,例如“#”或“\”?

我真的不想使用替换,只是返回 true 或 false。

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

陪你到最终 2024-08-11 05:56:41

使用函数 strstr https://www.php.net/manual/en/ function.strstr.php
返回从第一次出现 Needle 到 haystack 末尾的 haystack 字符串的一部分

注意:如果您只想确定特定的 Needle 是否出现在 haystack 中,请改用更快、内存占用更少的函数 strpos()。

use the function strstr https://www.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.

她如夕阳 2024-08-11 05:56:41

如果您只想知道字符串是否包含,可以使用 strpos 函数另一个(你的问题内容似乎表明了这一点,即使你的标题说“删除”)

注意:不要忘记使用 !===== 运算符,因为该函数可以返回 0 或 false,并且它们具有不同的含义。

如果您想“删除”字符,str_replacestrtr 可能可以解决问题。

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.

小糖芽 2024-08-11 05:56:41

您可以执行以下操作:

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

特别注意 !== 语法,它区分 false (表示未找到该字符)和 0 code> (意味着它是在位置 0 处找到的)。

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

归属感 2024-08-11 05:56:41

尝试正则表达式。

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

注意:您必须将反斜杠“\”转义三次。

如果您确实希望它们采用布尔格式,则可以使用 三元运算符 '?:' 这样

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

或者简单地转换为布尔值

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文