PHP

php strrpos能干嘛用

小樊
81
2024-11-19 19:02:53
栏目: 编程语言

strrpos() 是 PHP 中的一个字符串函数,它用于查找一个字符串中最后一个指定子字符串出现的位置

以下是 strrpos() 函数的一些常见用法:

  1. 在字符串中查找子字符串的最后一次出现位置:
$haystack = 'Hello, welcome to the world of PHP!';
$needle = 'PHP';
$position = strrpos($haystack, $needle);
echo "The last occurrence of '{$needle}' is at position: {$position}\n"; // 输出 "The last occurrence of 'PHP' is at position: 27"
  1. 检查子字符串是否存在于字符串中:
$haystack = 'Hello, welcome to the world of PHP!';
$needle = 'Python';
$position = strrpos($haystack, $needle);
if ($position !== false) {
    echo "The string '{$needle}' is found at position: {$position}\n";
} else {
    echo "The string '{$needle}' is not found in the given string.\n";
} // 输出 "The string 'Python' is not found in the given string."
  1. 从字符串末尾开始查找子字符串:
$haystack = 'Hello, welcome to the world of PHP!';
$needle = 'PHP';
$position = strrpos($haystack, $needle);
if ($position !== false) {
    echo "The last occurrence of '{$needle}' is at position: {$position}\n"; // 输出 "The last occurrence of 'PHP' is at position: 27"
} else {
    echo "The string '{$needle}' is not found in the given string.\n";
}

总之,strrpos() 函数在处理字符串时非常有用,尤其是在需要查找子字符串在字符串中最后一次出现位置的情况下。

0
看了该问题的人还看了