• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

php 搞代码 3年前 (2022-01-25) 11次浏览 已收录 0个评论

兼容:(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@本文9来源gao($daima.com搞@代@#码8网^搞代gaodaima码 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


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:字符串函数库-搜索类型_PHP

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址