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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP