【问题标题】:Needle is in haystack but barn door is jammed shut!针在干草堆里,但谷仓门被卡住了!
【发布时间】:2011-01-27 20:21:10
【问题描述】:

当 $haystack = "my keyword" 和 $needle = "my keyword" 时,下面的测试返回 false ($pos = 0),大概是因为我的 stripos 测试返回 0,因为谷仓中没有空白空间。

在这种情况下,我需要在比较中进行哪些更改才能返回 true?

function my_test($post){
    if($post->post_title == "") return false;
    $haystack = my_esc2($post->post_title);
    $needle = trim(my_getKeyword($post));
    $pos = stripos($haystack, $needle);
    if ($pos !== false) return true;
    //returns 0 when $needle and $haystack are the same exact phrase. but should return 1
}

function my_getKeyword($post)
{
    $myKeyword = get_post_meta($post->ID, '_my_keyword', true);
    if($myKeyword == "") $myKeyword = $post->post_title;
    $myKeyword = my_esc($myKeyword);
    return " ".$myKeyword;
}

function my_esc($str, $quotation='"') {
    if ($quotation != '"' && $quotation != "'") return false;
    return str_replace($quotation, $quotation.$quotation, $str);
}

function my_esc2($str, $quotation='"') {
    if ($quotation != '"' && $quotation != "'") return false;
    return str_replace($quotation, '', $str);
}

【问题讨论】:

  • 什么返回 0? stripos()my_test()?
  • 函数my_escmy_esc2有什么作用?特别是,给出这条评论的函数的输出是什么?以这种方式摆脱“'”是错误的(改用trim
  • my_test 只会在$post->post_title == false 时返回布尔值false。否则它将返回truenull

标签: php


【解决方案1】:

如果两个字符串相同,stripos 应该返回 0,因为 0 是字符串中找到匹配项的位置。

但是,您使用的是!== 运算符,因此无论如何测试都应该返回true(顺便说一句,您可以只使用return ($pos !== false))。

您确定您正在理解该语句,您能否在return 语句之前同时回显$haystack$needle

在我看来,haystack 和 needle 不一样或者没有找到 needle或者($post->post_title == "")...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    相关资源
    最近更新 更多