教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 php中STRPOS查找失败返回的是FALSE注意事项

php中STRPOS查找失败返回的是FALSE注意事项

发布时间:2016-10-09   编辑:jiaochengji.com
教程集为您提供php中STRPOS查找失败返回的是FALSE注意事项等资源,欢迎您收藏本站,我们将为您提供最新的php中STRPOS查找失败返回的是FALSE注意事项资源
strpos() 函数返回字符串在另一个字符串中第一次出现的位置了,但是我们在按官方的手册来测试时发现一直返回false了,那么要如何来解决

STRPOS用法

strpos(string,find,start)

我们看看strpos的一段代码:

//ajax获取分词
public function get_segment_words() {
 $title = I('title');
 $content = I('content');
 $Segment = M('Segment');
 $Segment_content = M('Segment_content');
 $segment_array = $Segment->getField('id,word');
 $setment_words = array();
 foreach ($segment_array as $id => $word) {
  if (false !== strpos($content, $word) || false !== strpos($title, $word)) {
   $segment_words[] = $word;
  }
 }
 $segment_words = array_unique($segment_words);
 $segment_words = implode(',', $segment_words);
 echo $segment_words;exit; //ajax获取填充
}

注意这句代码:

if (false !== strpos($content, $word) || false !== strpos($title, $word)) {
//TODO
}

如果匹配失败,strpos会返回bool类型的false,这个一定要注意。不然会出现什么情况呢?假如你要匹配的字符正好在第一个位置,对于strpos这个函数来说返回的是0,也就是位置0.这个时候实际上是匹配到了,结果返回0,如果这样判断就错了:

if (!strpos($content, $word))

举个例子:

内容:购物袋范德萨法拉点撒范德萨。

匹配:购物

如果要找内容里面是否有“购物”两个字,strpos会返回0,表示存在“购物”两个字,位置是0.

因此要用false!=strpos($find,$content)来判断匹配是否成功。

您可能感兴趣的文章:
php中STRPOS查找失败返回的是FALSE注意事项
php strstr、stristr、strpos函数比较
PHP学习之使用 strpos()函数时的注意事项
php获取本机的局域网(内网)IP地址的代码与函数说明
PHP获取本机的局域网IP地址方法
php判断是否包含字符
php中用于查找字符串的常用函数
php strpos是什么
php检测字符串是否包含字符串
php字符串查找函数(strrpos与strchr)

[关闭]
~ ~