在PHP中,有以下幾種方法可以檢測一個字符串是否包含另一個字符串:
$haystack = 'hello world';
$needle = 'world';
if (strpos($haystack, $needle) !== false) {
echo '包含';
} else {
echo '不包含';
}
$haystack = 'hello world';
$needle = 'world';
if (strstr($haystack, $needle)) {
echo '包含';
} else {
echo '不包含';
}
$haystack = 'hello world hello';
$needle = 'hello';
$count = substr_count($haystack, $needle);
if ($count > 0) {
echo '包含';
} else {
echo '不包含';
}
這些方法可以根據實際需求選擇使用哪一種來檢測字符串的包含關系。