簡體   English   中英

從字符串數組中搜索關鍵字(PHP)

[英]Search keywords from array in string (PHP)

$array_keywords = ('red','blue','green');
$string = "Sometimes I'm happy, Sometimes I'm blue, Sometimes I'm sad";

(PHP)在字符串中搜索關鍵字(從數組中)並打印符合項,在這種情況下,期望的結果應返回“ blue ”。

我該怎么做?

用這個:

$array_keywords = array('red','blue','green');

$string = 'Sometimes I'm happy, Sometimes I'm blue, Sometimes I'm sad';

foreach ($array_keywords as $keys) {
    if (strpos($string, $keys)) {
        echo "Match found"; 
        return true;
    }
}
echo "Not found!";
return false;

您也可以使用stristr()stripos()檢查不區分大小寫。

或者您可以看到Lucanos的答案

檢查此代碼,

<?php
function strpos_array($haystack, $needles, &$str_return) {

    if ( is_array($needles) ) {
        foreach ($needles as $str) {
            if ( is_array($str) ) {
                $pos = strpos_array($haystack, $str);
            } else {
                $pos = strpos($haystack, $str);
            }

            if ($pos !== FALSE) {
                $str_return[] = $str;
            }
        }
    } else {
        return strpos($haystack, $needles);
    }
}

// Test
$str = [];
$array_keywords = ('red','blue','green');
$string = "Sometimes I'm happy, Sometimes I'm blue, Sometimes I'm sad";

strpos_array($string, $array_keywords,$str_return); 
print_r($str_return);
?>

這是帶有數組的高級strpos代碼。

滿足您要求的更精確方法是,如果匹配多個元素,則獲得數組。

暫無
暫無

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

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