📅  最后修改于: 2023-12-03 15:05:23.382000             🧑  作者: Mango
PHP是一种广泛使用的开源脚本语言,用于Web开发和服务器端脚本编写。strpos()是PHP中用于在字符串中查找子字符串的函数。
strpos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : mixed
在检查haystack字符串中是否包含needle字符串时,该函数返回needle第一次出现的位置。如果没有找到needle,函数返回false。
$text = 'I love PHP';
$pos = strpos($text, 'love');
if ($pos !== false) {
echo 'The word "love" was found in the string "' . $text . '" at position ' . $pos;
} else {
echo 'The word "love" was not found in the string "' . $text . '"';
}
输出:
The word "love" was found in the string "I love PHP" at position 2
$people = array('Mary', 'Tom', 'Joe');
if (strpos(implode(',', $people), 'Mary') !== false) {
echo "Mary is in the array";
} else {
echo "Mary is not in the array";
}
输出:
Mary is in the array
$text = 'I love PHP';
$pos = strpos($text, 'PHP', 5); //从第6个字符开始查找
if ($pos !== false) {
echo 'The word "PHP" was found in the string "' . $text . '" at position ' . $pos;
} else {
echo 'The word "PHP" was not found in the string "' . $text . '"';
}
输出:
The word "PHP" was found in the string "I love PHP" at position 8
strpos()是PHP中非常有用的函数,它允许程序员查找和处理字符串。程序员可以使用它来确定字符串是否包含特定的子字符串,并在需要时指定偏移量。