📅  最后修改于: 2023-12-03 14:53:26.664000             🧑  作者: Mango
在 PHP 中,我们可以使用一些内置函数来查找一个字符串是否包含了另一个字符串。这些函数包括:
strpos()
: 查找一个子字符串在另一个字符串中第一次出现的位置。stripos()
: 查找一个子字符串在另一个字符串中第一次出现的位置(忽略大小写)。substr_count()
: 统计一个字符串在另一个字符串中出现的次数。strstr()
: 查找一个子字符串在另一个字符串中第一次出现的位置,并返回从该位置到字符串结尾的子字符串。stristr()
: 查找一个子字符串在另一个字符串中第一次出现的位置,并返回从该位置到字符串结尾的子字符串(忽略大小写)。strpos()
$haystack = 'This is a sample string containing PHP';
$needle = 'PHP';
if (strpos($haystack, $needle) !== false) {
echo 'The string "'.$needle.'" was found in the string "'.$haystack.'".';
} else {
echo 'The string "'.$needle.'" was not found in the string "'.$haystack.'".';
}
输出:
The string "PHP" was found in the string "This is a sample string containing PHP".
stripos()
$haystack = 'This is a sample string containing php';
$needle = 'PHP';
if (stripos($haystack, $needle) !== false) {
echo 'The string "'.$needle.'" was found in the string "'.$haystack.'".';
} else {
echo 'The string "'.$needle.'" was not found in the string "'.$haystack.'".';
}
输出:
The string "PHP" was found in the string "This is a sample string containing php".
substr_count()
$haystack = 'This is a sample string containing PHP, PHP and more PHP';
$needle = 'PHP';
$count = substr_count($haystack, $needle);
echo 'The string "'.$needle.'" was found '.$count.' times in the string "'.$haystack.'".';
输出:
The string "PHP" was found 3 times in the string "This is a sample string containing PHP, PHP and more PHP".
strstr()
$haystack = 'This is a sample string containing PHP';
$needle = 'string';
$substring = strstr($haystack, $needle);
echo 'The string "'.$needle.'" was found in the string "'.$haystack.'". The substring starting from this position is "'.$substring.'".';
输出:
The string "string" was found in the string "This is a sample string containing PHP". The substring starting from this position is "string containing PHP".
stristr()
$haystack = 'This is a sample string containing php';
$needle = 'String';
$substring = stristr($haystack, $needle);
echo 'The string "'.$needle.'" was found in the string "'.$haystack.'" (case insensitive). The substring starting from this position is "'.$substring.'".';
输出:
The string "String" was found in the string "This is a sample string containing php" (case insensitive). The substring starting from this position is "string containing php".
以上是一些常见的处理字符串包含问题的使用示例,具体的函数参数、返回值请详细参考 PHP 官方文档。