当前位置:Gxlcms > PHP教程 > 字符串函数库-搜索类型_PHP

字符串函数库-搜索类型_PHP

时间:2021-07-01 10:21:17 帮助过:5人阅读

兼容:(PHP 3, PHP 4, PHP 5)
strpos -- Find position of first occurrence of a string
查找字符在字符串第一次出现的位置

语法:int strpos ( string haystack, mixed needle [, int offset] )
返回值:整数
函数种类: 资料处理

内容说明:
英文:
Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the strrpos(), this function can take a full string as the needle parameter and the entire string will be used.
If needle is not found, strpos() will return boolean FALSE.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
The optional offset parameter allows you to specify which character in haystack to start searching. The position returned is still relative to the beginning of haystack.

中文:
传回参数 needle在字串 haystack中第一次出现的位置,以数字表示。不像strrpos( ),此函式可以取参数 needle全部的字串,而且会使用全部的字串。如果找不到参数 needle,则传回 false。

如果参数 needle不是字串时,它会转换成整数并且按照字元的顺序值来使用。
参数 offset允许你去指定在 haystack中从那一个字元开始搜寻,传回的位置依然是相对於 haystack的起点。

*值得注意的是 needle 只能是一个字符,中文字等就不适合了。

例子讲解:
php

$mystring
= 'abc';

$findme= 'a';

$pos = strpos($mystring, $findme);



// Note our use of ===.Simply == would not work as expected

// because the position of 'a' 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 \" and exists at position $pos\";

}



// We can search for the character, ignoring anything before the offset

$newstring = 'abcdef abcdef';

$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0

?>

strpos()与substr_count()对比:
php

$mystring
= "Hello Chris\";

if (substr_count($mystring, \"Hello\") == 0)

echo \"no\";

// same as:

if (strpos($mystring, \"Hello\") === false)

echo \"no\";

?>


对比下面两个代码注意数字情况下,容易出现的错误,数字整数情况下不能看成字符串。
php

$val1
=123;

$val2="123,456,789\";

if (strpos($val2, $val1)!==false) echo \"matched\";

else echo \"not matched\";

?>

结果为: not matched

php

$val1
=(string)123;

$val2="123,456,789\";

if (strpos($val2, $val1)!==false) echo \"matched\";

else echo \"not matched\";

?>

结果为:not matched

人气教程排行