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

PHP函数使用简介:strpos()查找字符串中某一子串的位置

发布时间:2023-06-23 13:49:40

php中strpos()函数是查找一个字符串中是否包含了某个子串,如果包含,返回该子串在原始字符串中的位置。

语法:

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

参数说明:

$haystack:表示原始字符串,即需要被查找的字符串。

$needle:表示要查找的子串。

$offset:表示查找起始点,如果不设置会从字符串的开头开始查找。

返回值:

该函数返回要查找的子串在原始字符串中的首次出现的位置,如果没有找到该子串,则该函数将返回FALSE。

使用示例:

1、查找一个字串

代码:

<?php

$findme    = 'a';

$mystring1 = 'xyz';

$mystring2 = 'ABCaabcd';

$pos1 = strpos($mystring1, $findme);

$pos2 = strpos($mystring2, $findme);

// 注意这里使用的是 ===。简单的 == 不能像我们期望的那样工作,因为 'a' 的位置是 0( 个字符)。

if ($pos1 === false) {

    echo "The string '$findme' was not found in the string '$mystring1'";

}

else {

    echo "The string '$findme' was found in the string '$mystring1'";

    echo " and exists at position $pos1";

}

if ($pos2 !== false) {

    echo "We found '$findme' in '$mystring2' at position $pos2";

}

?>

输出:

The string 'a' was not found in the string 'xyz'We found 'a' in 'ABCaabcd' at position 3

2、查找多个字串,以及设置查找起始点

代码:

<?php

$mystring = 'abc';

$findme   = 'a';

$pos = strpos($mystring, $findme, 1); // 从位置1开始查找$a

// 注意这里使用的是 ===。简单的 == 不能像我们期望的那样工作,因为 'a' 的位置是 0( 个字符)。

if ($pos === false) {

    echo "The string '$findme' was not found in the string '$mystring'";

} else {

    echo "The string '$findme' was found in the string '$mystring'";

    echo " and exists at position $pos";

}

?>

输出:

The string 'a' was not found in the string 'abc'

3、使用strpos()函数查找字符串中的子串

代码:

<?php

$string = 'Hello world. The world is nice and world is great';

$findme1 = 'world';

$findme2 = 'Hello';

$pos1 = strpos($string, $findme1); 

$pos2 = strpos($string, $findme2); 

echo "pos1:".$pos1.", pos2:".$pos2;

?>

输出:

pos1:6, pos2:0

总结:

strpos()函数在PHP中是极为常用的一个函数,具有很大的实用价值,能在很多实际编程过程中派上用场。需要注意的是,strpos()的函数返回值有可能是FALSE,所以在使用时应该使用"==="来进行判断,判断其值以及数据类型是否等于FALSE。