简体   繁体   中英

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. Please help. Thanks

NB: I've found if I put $matchtag = "quote"; before in_array it works fine. So is there any problem with the formatting of $matchtag variable?

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.

Consider changing the regex to '/\\b#otw[0-9a-z]+\\b/i instead; \\b is a zero-length token that won't interfere with what is captured.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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