php 如果字符串包含正斜杠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11225413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:00:56  来源:igfitidea点击:

If string contains forward slash

phpstringif-statement

提问by Msmit1993

How do i make a if statement which checks if the string contains a forward slash?

我如何创建一个 if 语句来检查字符串是否包含正斜杠?

$string = "Test/Test";   
if($string .......)
{
    mysql_query(""); 
} 
else 
{
    echo "the value contains a invalid character"; 
} 

回答by Mike Mackintosh

You can use strpos, which will make sure there is a forward slash in the string but you need to run it through an equation to make sure it's not false. Here you can use strstr(). Its short and simple code, and gets the job done!

您可以使用 strpos,这将确保字符串中有一个正斜杠,但您需要通过等式运行它以确保它不是错误的。在这里您可以使用strstr()。它的代码简短而简单,可以完成工作!

if(strstr($string, '/')){
    //....
}

For those who live and die by the manual, when the haystack is very large, or the needle is very small, it is quicker to use strstr(), despite what the manual says.

对于那些靠手册生死存亡的人来说,当大海捞针很大,或者针很小的时候strstr(),不管手册怎么说,使用起来会更快。

Example:

例子:

Using strpos(): 0.00043487548828125

使用strpos():0.00043487548828125

Using strstr(): 0.00023317337036133

使用strstr():0.00023317337036133

回答by Rawkode

if(strpos($string, '/') !== false) {
  // string contains /
}

From the PHP manual of strstr:

来自strstr的 PHP 手册:

Note:

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

笔记:

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

回答by infojolt

Use strpos()

strpos()

If it doesn't return false, the character was matched.

如果它不返回 false,则该字符已匹配。