PHP 寻找字符串
在PHP中,寻找字符串可以通过多种方式实现,这取决于你具体的需求,比如是查找一个子串在另一个字符串中的位置,还是检查一个字符串是否包含另一个字符串等。下面是一些常用的方法:
1. 使用 strpos() 函数
strpos() 函数用于查找字符串的首次出现位置。
[PHP] 纯文本查看 复制代码 $string = "Hello, world!";
$findMe = "world";
$pos = strpos($string, $findMe);
if ($pos === false) {
echo "The string '$findMe' was not found in the string.";
} else {
echo "The string '$findMe' was found in the string.";
echo " and exists at position $pos.";
}
2. 使用 stripos() 函数
stripos() 函数与 strpos() 类似,但它不区分大小写。
[PHP] 纯文本查看 复制代码 $string = "Hello, world!";
$findMe = "WORLD";
$pos = stripos($string, $findMe);
if ($pos === false) {
echo "The string '$findMe' was not found in the string.";
} else {
echo "The string '$findMe' was found in the string.";
echo " and exists at position $pos.";
}
3. 使用 strstr() 或 stristr() 函数
这些函数用于查找字符串的首次出现并返回从该位置到字符串末尾的所有字符。stristr() 版本不区分大小写。
[PHP] 纯文本查看 复制代码 $string = "Hello, world!";
$findMe = "world";
$part = stristr($string, $findMe);
if ($part !== false) {
echo "The string '$findMe' was found in the string.";
echo " and the rest of the string is: $part";
} else {
echo "The string '$findMe' was not found in the string.";
}
4. 使用 str_contains() 函数(PHP 8.0+)
从PHP 8.0开始,可以使用str_contains()函数来检查一个字符串是否包含另一个字符串。这个函数返回一个布尔值。
[PHP] 纯文本查看 复制代码 $string = "Hello, world!";
$findMe = "world";
if (str_contains($string, $findMe)) {
echo "The string '$findMe' was found in the string.";
} else {
echo "The string '$findMe' was not found in the string.";
}
5. 使用 mb_strpos() 函数(多字节支持)
对于多字节字符集(如UTF-8),可以使用mb_strpos()函数。这个函数提供了对多字节字符的正确支持。
[PHP] 纯文本查看 复制代码 $string = "你好,世界!"; // 注意这里的字符不是简单的ASCII字符,而是UTF-8编码的汉字。
$findMe = "世界";
$pos = mb_strpos($string, $findMe);
if ($pos === false) {
echo "The string '$findMe' was not found in the string.";
} else {
echo "The string '$findMe' was found in the string.";
echo " and exists at position $pos.";
}
选择合适的方法取决于你的具体需求,比如是否需要考虑大小写、是否需要返回位置还是直接返回子串等。
|