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

PHP函数之strpos():查找字符串中的子字符串并返回其位置

发布时间:2023-06-16 09:58:03

PHP函数strpos()是用于查找一个字符串中是否包含另一个子字符串的函数。如果该子字符串存在,则返回其在主字符串中的位置,如果不存在,则返回false。在本文中,我们将学习如何使用PHP函数strpos()来查找字符串中的子字符串并返回其位置。

语法:

strpos(string,find,start)

参数:

string 是必需的。被搜索的字符串。

find 是必需的。要查找的子字符串。

start 是可选的。指定搜索开始的位置。

示例:

让我们来看一下一个使用strpos()函数的例子,以便您可以更好地了解其使用方法。

<?php  
$str = "Hello World";  
$pos = strpos($str, "World");  
if ($pos === false) {  
    echo "The string 'World' was not found in the string 'Hello World'";  
} else {  
    echo "The string 'World' was found in the string 'Hello World' at position " . $pos;  
}  
?>

该程序的输出为:

The string 'World' was found in the string 'Hello World' at position 6

在这个例子中,我们使用了PHP函数strpos()来查找字符串“Hello World”中是否包含了子字符串“World”。如果字符串被找到了,将会返回该字符串在主字符串中的位置,否则返回false。

注意:因为该函数在字符串中从0开始计数,所以在这个例子中我们看到字母“W”在字符串中的位置是6。

现在让我们来看一下如何使用PHP函数strpos()来查找一个子字符串在另一个字符串中的位置并返回它。

查找一个子字符串在另一个字符串中的位置并返回它:

以下是在另一个字符串中查找一个子字符串的位置并返回它的例子。

<?php  
$str = "This is a test string.";  
$needle = "test";  
$pos = strpos($str, $needle);  
if ($pos === false) {  
    echo "The string '$needle' was not found in the string '$str'";  
} else {  
    echo "The string '$needle' was found in the string '$str' at position " . $pos;  
}  
?>

该程序的输出为:

The string 'test' was found in the string 'This is a test string.' at position 10

在这个例子中,我们在字符串“This is a test string.”中查找子字符串“test”,并返回“test”在字符串中的位置。

现在让我们来看一下如何在指定的位置开始搜索字符串中的子字符串。

从指定位置开始搜索字符串中的子字符串:

以下是在指定位置开始搜索字符串中的子字符串的例子。

<?php  
$str = "Hello World!";  
$needle = "World";  
$startpos = 6;  
$pos = strpos($str, $needle, $startpos);  
if ($pos === false) {  
    echo "The string '$needle' was not found in the string '$str'";  
} else {  
    echo "The string '$needle' was found in the string '$str' at position " . $pos;  
}  
?>

该程序的输出为:

The string 'World' was found in the string 'Hello World!' at position 6

在这个例子中,我们在字符串“Hello World!”中开始在位置6处查找子串“World”。

到目前为止,我向您展示了如何使用PHP函数strpos()来查找字符串中的子字符串并返回其位置。如果有任何问题或疑问,请不要犹豫,欢迎在下面留言,我会尽快给您答复。