欢迎访问宙启技术站
智能推送

PHP里如何使用strpos函数

发布时间:2023-06-30 15:11:47

PHP中使用strpos()函数可以用来查找字符串中的特定子串的位置。该函数返回的是子串在字符串中 次出现的位置,如果没有找到则返回false。下面是使用strpos()函数的不同用法和示例:

1. 基本用法:

$string = 'Hello, World!';
$substring = 'World';

$position = strpos($string, $substring);

if ($position !== false) {
    echo "Substring found at position: " . $position;
} else {
    echo "Substring not found";
}

结果将输出:Substring found at position: 7。说明在字符串$string中找到了子串$substring,并返回了它在字符串中的位置。

2. 查找子串的第二次出现的位置:

$string = 'Hello, World! Hello, PHP!';
$substring = 'Hello';

$position = strpos($string, $substring);
$position = strpos($string, $substring, $position + strlen($substring));

if ($position !== false) {
    echo "Second occurrence found at position: " . $position;
} else {
    echo "Second occurrence not found";
}

结果将输出:Second occurrence found at position: 14strpos()函数接受一个可选的第三个参数,用于指定搜索的起始位置。在这个例子中,使用了上一次查找到的位置+子串的长度作为起始位置,以便继续查找下一次出现的位置。

3. 大小写敏感的查找:

$string = 'Hello, World!';
$substring = 'WORLD';

$position = strpos($string, $substring);

if ($position !== false) {
    echo "Substring found at position: " . $position;
} else {
    echo "Substring not found";
}

结果将输出:Substring not found。由于默认情况下strpos()函数是大小写敏感的,所以在这个例子中没有找到子串$substring

4. 大小写不敏感的查找:

$string = 'Hello, World!';
$substring = 'WORLD';

$position = stripos($string, $substring);

if ($position !== false) {
    echo "Substring found at position: " . $position;
} else {
    echo "Substring not found";
}

结果将输出:Substring found at position: 7。使用stripos()函数可以实现大小写不敏感的查找。

5. 从字符串末尾开始查找:

$string = 'Hello, World!';
$substring = 'World';

$position = strrpos($string, $substring);

if ($position !== false) {
    echo "Last occurrence found at position: " . $position;
} else {
    echo "Substring not found";
}

结果将输出:Last occurrence found at position: 7strrpos()函数可以从字符串的末尾开始查找最后一次出现的位置。

在使用strpos()函数时,还可以结合其他字符串处理函数和控制流语句,根据具体需求进行字符串查找和处理。