簡體   English   中英

in_array函數無法按預期工作

[英]in_array function not working as expected

我正在編寫一個簡單的代碼,但無法准確找到我要去的地方。

$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;
}

現在當我使用

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

一切正常。 但是帶有變量$ matchtag,它返回false。 請幫忙。 謝謝

注意:我發現如果我把$matchtag = "quote"; 在in_array之前可以正常工作。 那么$matchtag變量的格式有問題嗎?

它返回false,因為您的正則表達式還捕獲了前面的空格字符(在前面的\\s ),因此您使用的是" quote"而不是"quote"

考慮將正則表達式改為'/\\b#otw[0-9a-z]+\\b/i \\b是一個零長度的令牌,不會干擾捕獲的內容。

如果不希望這樣做,則可以選擇使用正向后視( (?<=\\s)而不是\\s ),使[0-9a-z]+部分成為自己的捕獲組(這也消除了對str_replace的需要)在測試之前在$matchtag上使用trim

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM