PHP 8 – 使用 str_contains() 檢查字串是否包含子字串


在 PHP 8 中,**str_contains** 函式用於確定字串是否包含給定的子字串。**str_contains** 函式檢查第一個字串是否包含在第二個字串中,並根據字串是否找到返回 true/false 布林值。這是一個不言自明的函式。

str_contains(string $haystack, string $needle): bool

示例 1:PHP 8 str_contains 函式。

<?php
   if (str_contains('great reading tutorial', 'tutorial')) {
      var_dump('Tutorial has been found');
   }
?>

輸出

string(23) "Tutorial has been found"

示例:str_contains 函式。

<?php
   if (str_contains('great reading tutorial', 'hello')){
      var_dump('great reading');
   }
?>

注意: 上面的程式返回 false,因為第一個字串不包含第二個字串。

strpos() 函式

在 PHP 7.x 中,strops() 函式用於檢查給定字串是否包含另一個字串。此函式返回 needle 字串的位置,如果未找到字串 needle,則返回 false。

if (strpos('string with lots of words', 'words') !== false) { /* … */ }

示例:PHP 7.x strops() 函式

 線上演示

<?php
   $string = 'Hello World!';
   if (strpos($string, 'Hello') !== false) {
      echo 'True';
   }
?>

輸出

True

更新於: 2021年4月1日

3K+ 瀏覽量

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.