简体   繁体   English

in_array函数无法按预期工作

[英]in_array function not working as expected

There is a simple code I'm writing but can't find exactly where I'm going wrong. 我正在编写一个简单的代码,但无法准确找到我要去的地方。

$data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget tellus cursus, ultrices justo at, ultricies libero. Vivamus consequat ante vel nunc dapibus, non tempus elit vehicula. Nulla facilisi. Proin leo urna, congue eu justo eget, viverra mattis lacus.
#otwquote";

preg_match_all('/\s#otw[0-9a-z]+\b/i', $data, $matches);
$matchtag = str_replace("#otw", "", strtolower($matches[0][0]));

echo $matchtag;

$formats = array("status", "aside", "link", "gallery", "image", "audio", "video", "quote", "chat", "standard");
$backhash ="standard";

// here $matchtag = "quote"

if ( in_array ( $matchtag , $formats ) ) {  
    echo $matchtag;
} else {
    echo $backhash;
}

Now when I'm using 现在当我使用

if ( in_array ( "quote" , $formats ) )

It's working fine. 一切正常。 But with variable $matchtag it's returning false. 但是带有变量$ matchtag,它返回false。 Please help. 请帮忙。 Thanks 谢谢

NB: I've found if I put $matchtag = "quote"; 注意:我发现如果我把$matchtag = "quote"; before in_array it works fine. 在in_array之前可以正常工作。 So is there any problem with the formatting of $matchtag variable? 那么$matchtag变量的格式有问题吗?

It's returning false because your regular expression also captures the preceding whitespace character (that \\s in front), so you are using " quote" and not "quote" as the needle. 它返回false,因为您的正则表达式还捕获了前面的空格字符(在前面的\\s ),因此您使用的是" quote"而不是"quote"

Consider changing the regex to '/\\b#otw[0-9a-z]+\\b/i instead; 考虑将正则表达式改为'/\\b#otw[0-9a-z]+\\b/i \\b is a zero-length token that won't interfere with what is captured. \\b是一个零长度的令牌,不会干扰捕获的内容。

If that is not desirable, alternatives include using positive lookbehind ( (?<=\\s) instead of \\s ), making the [0-9a-z]+ part its own capturing group (this would also obviate the need for str_replace ) and using trim on $matchtag before the test. 如果不希望这样做,则可以选择使用正向后视( (?<=\\s)而不是\\s ),使[0-9a-z]+部分成为自己的捕获组(这也消除了对str_replace的需要)在测试之前在$matchtag上使用trim

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM