首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >php strpos没有正确计算?

php strpos没有正确计算?
EN

Stack Overflow用户
提问于 2013-02-19 22:46:18
回答 3查看 1K关注 0票数 0

因此,我遇到了与这篇文章类似的问题:PHP strpos not working,但不完全是。

下面是我的情况(来自CodeIgniter应用程序):

代码语言:javascript
复制
$_submit = strtolower($this->input->post('form-submit'));

if(strpos('save', $_submit) !== FALSE){
    // we have to save our post data to the db
}
if(strpos('next'), $_submit) !== FALSE){
    // we have to get the next record from the db
}

问题是,尽管form-submit包含这两个值中的一个或两个,但这两个值实际上都不会触发。form-submit接收的值是:“save”、“save-next”和“skip-next”(我已经通过查看post数据确认了这一点)。现在,对于真正的抓手,我在相同的代码块中也有这一行:

代码语言:javascript
复制
if ($_submit === 'add-comment'){
    //do something
}

这是非常好用的。所以===可以像预期的那样工作,但是!==不是吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-02-19 22:53:23

你给strpos函数提供了错误的参数......

代码语言:javascript
复制
$submit = strtolower($this->input->post('form-submit'));

if(strpos($submit,'save') !== FALSE){
    // we have to save our post data to the db
}
if(strpos($submit,'next') !== FALSE){
    // we have to get the next record from the db
}

请查看php.net中的strpos函数manual....first参数是完整字符串,第二个参数是密钥字符串

你也可以在这里找到一个小的example

票数 4
EN

Stack Overflow用户

发布于 2013-02-19 22:53:47

您对strpos的参数是错误的:作为the manual states,它是strpos ( string $haystack , mixed $needle )。在您的代码中,您将在草堆'save'中查找针$_submit

所以if(strpos($_submit, 'save') !== FALSE)

当然,在测试'save''save'时,这两种方法都可以工作,这可能是您感到困惑的原因。

票数 2
EN

Stack Overflow用户

发布于 2013-02-19 22:53:13

我建议使用switch而不是多个if条件。

代码语言:javascript
复制
$_submit = strtolower($this->input->post('form-submit'));

switch($_submit) {
    case 'save':
    case 'save-comment': // example for different spelling but same action...
         // we have to save our post data to the db
    break;
    case 'next':
         // we have to get the next record from the db
    break;
    case 'add-comment':
         // we have to save our post data to the db
    break;
    default:
        die('Unknown parameter value');
    break;
} 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14960253

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档