php-strpos 判斷一個字符串是否存在於另一個字符串中

在 PHP 中,你可以使用 strpos() 函數來判斷一個字符串(例如 "play")是否存在於另一個字符串中。strpos() 函數會返回子字符串在原始字符串中首次出現的位置(索引從 0 開始),如果子字符串不存在,則返回 false。

以下是一個簡單的示例:

$string = "I like to play basketball";  
$substring = "play";  
  
if (strpos($string, $substring) !== false) {  
    echo "字符串 '$string' 中包含 '$substring'。";  
} else {  
    echo "字符串 '$string' 中不包含 '$substring'。";  
}

在這個示例中,strpos($string, $substring) 會返回 "play" 在 "$string" 中首次出現的位置(在這種情況下是 7),然後 !== false 檢查確保位置不是 false(即 "play" 確實存在於字符串中)。如果 "play" 存在於字符串中,就會輸出相應的消息。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章