PHP 字符串 strpos()函数
strops()是PHP的内置函数。它用于找到一个字符串在另一个字符串或子字符串中第一次出现的位置。
语法
int strpos ( string haystack , mixedneedle [, int $offset = 0 ] );
参数 | 描述 | 必需/可选 |
---|---|---|
字符串 | 指定要搜索的字符串。 | 开始 |
查找 | 指定要查找的字符串。 | 必需 |
开始位置 | 指定搜索开始的位置。 | 可选 |
此函数将帮助我们在haystack字符串中找到needle的第一个出现的数值位置
注意:strops()函数区分大小写,并且对二进制数据安全。
示例1
<?php
str1="Hello Php";str2="Hello Php javatpoint!";
echo "First string is: ".str1;
echo "<br>";
echo "First string is: ".str2;
echo "<br>";
echo "By using 'strpos()' function:".strpos("str1,str2","php");
//str1 andstr2 'Php'first letter is upper case so output is nothing.
// It is case-sensitive
?>
输出:
First string is: Hello Php
First string is: Hello Php javatpoint!
By using 'strpos()' function:
示例2
<?php
str1="Hello php";str2=" Hello php javatpoint!";
echo "First string is: ".str1;
echo "<br>";
echo "First string is: ".str2;
echo "<br>";
echo "By using 'strpos()' function:".strpos("str1,str2","php");
//Find the position of the first occurrence of "php" inside the string
?>
输出:
First string is: Hello php
First string is: Hello php javatpoint!
By using 'strpos()' function:6
示例3
<?php
mystring = 'Hello PHP';findme = 'Hello';
pos = strpos(mystring, findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'Hello' was the 0th (first) character.
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 "<br>";
echo " and exists at position $pos";
}
?>
输出:
The string 'Hello' was found in the string 'Hello PHP'
and exists at position 0
参见
strchr():用于在另一个字符串中查找第一个出现的字符串。
strcoll() :基于区域设置的字符串比较。
strcmp():二进制安全的字符串比较。
参考:
http://php.net/manual/en/function.strpos.php