- 注册时间
- 2010-11-11
- 最后登录
- 2025-5-27
- 阅读权限
- 200
- 积分
- 14361
- 精华
- 2
- 帖子
- 843
  

TA的每日心情 | 无聊 2025-5-27 03:37:20 |
---|
签到天数: 366 天 [LV.9]以坛为家II
我玩的应用:
  
|
在研究浏览器跳转的时候,因为不懂PHP,只好七拼八凑的弄了一段判断浏览器语音的代码 ,试用了php strpos的函数
函数如下:
$l1=$_SERVER["HTTP_ACCEPT_LANGUAGE"];//获取浏览器语言
$l2="zh";//赋予l2 zh的值,即判断中文
if ( strpos($l1,$l2) == false ){
echo "englsh";}//如果不含有zh则显示英文
else{
echo "中文";//如果含有zh则显示中文
}
当我满怀信心的写下这段代码的 时候,我悲剧 发现 无论如何,他都显示一样的结果。
于是百度谷歌之,查清该具体的函数的意义
如果你是个新手,如果你使用了strpos和stripos,如果你想通过这个函数查找的字符串就在开始出,那么是否会感到一点蛋疼。。。。
当你满怀信心的写下:
if (strpos($foo, “my”)==0) { echo(‘I find!’);}
你会惊喜的发现,无论如何,这个判断总是成立。。。。
php手册上说:strpos和stripos在找不到的情况下返回false,但是也可能返回0,或者”"。关键是如果要找的东西在一开始,那么返回的也是0。。。迷惑吗?实际上strpos或这stripos并不会在找不到的情况下返回0,只是false==0。晕吧。。哈哈。
其实由于php是弱类型,因此false==0;但是它还有个判定符===,使用===时,false和0就是两回事了,因此,代码得改成:
if (strpos($foo, “my”)===0) { echo(‘I find!’);}
另外附上一段php代码,具体可以运行看其演示
<?php
/*
判断字符串是否存在的函数
*/
function strexists($haystack, $needle) {
return !(strpos($haystack, $needle) === FALSE);//注意这里的"==="
}
/*
Test
*/
$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.
// 简单的使用 "==" 号是不会起作用的,需要使用 "===",因为 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";
}
// We can search for the character, ignoring anything before the offset
// 在搜索字符的时候可以使用参数 offset 来指定偏移量
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
?>
|
|