华域联盟 PHP php常用字符串查找函数strstr()与strpos()实例分析

php常用字符串查找函数strstr()与strpos()实例分析

本文实例讲述了php常用字符串查找函数strstr()与strpos()。分享给大家供大家参考,具体如下:

一句话使用strpos判断 ===!==,这样才能达到预期的效果,性能要比strstr要好,只是判断是否包含某个字符串就用这个了。

string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

1、$haystack被查找的字符串,$needle要查找的内容
2、如查找到则返回字符串的一部分,如没找到则返回FALSE
3、该函数区分大小写,如果想要不区分大小写,请使用 stristr()
4、如果你仅仅想确定needle是否存在于haystack中请使用速度更快、耗费内存更少的strpos()函数

<?php
 $email = '[email protected]';
 $domain = strstr($email,'@');
 $name = strstr($email,'@',TRUE);
 $no_con = strstr($email,'99');
 echo $domain; //输出 @example.com
 echo $name;  //输出name 从 PHP 5.3.0 起
 var_dump($no_con); //如果没找到,则返回布尔值 FALSE
?>

运行结果:

@example.com
name
bool(false)

mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

1、$haystack被查找的字符串,$needle要查找的内容
2、返回 needle 在 haystack 中首次出现的数字位置
3、该函数区分大小写,如果想要不区分大小写,请使用 stripos()
4、返回值,如找到的话,返回needle 存在于 haystack 字符串起始的位置(注意字符串位置是从0开始,而不是从1开始),没找到则返回FALSE,但也可能返回等同于 FALSE 的非布尔值

<?php
 $mystring = 'abc' ;
 $findme = 'a' ;
 $pos = strpos($mystring,$findme);
 echo $pos; //输出0,既是当前a的位置
?>

运行结果:

0

这里2个比较相似的函数,在这里简单介绍下,只需记住有这个函数即可,用时简单看下手册。

1、strrpos(),计算指定字符串在目标字符串中最后一次出现的位置

实例1 使用 ===

<?php
$mystring = 'abc';
$findme  = 'a';
$pos = strpos($mystring, $findme);

// 注意这里使用的是 ===。简单的 == 不能像我们期待的那样工作,
// 因为 '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";
}
?>

实例2 使用 !==

<?php
$mystring = 'abc';
$findme  = 'a';
$pos = strpos($mystring, $findme);

// 使用 !== 操作符。使用 != 不能像我们期待的那样工作,
// 因为 'a' 的位置是 0。语句 (0 != false) 的结果是 false。
if ($pos !== false) {
   echo "The string '$findme' was found in the string '$mystring'";
     echo " and exists at position $pos";
} else {
   echo "The string '$findme' was not found in the string '$mystring'";
}
?>

实例3 使用位置偏移量

<?php
// 忽视位置偏移量之前的字符进行查找
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, 不是 0
?>

注释
Note: 此函数可安全用于二进制对象。

2、strripos(),计算指定字符串在目标字符串中最后一次出现的位置(不区分大小写)

总结:注意这几个函数如果没找到时则会返回FALSE,故在判断两边是否相等时候(if),注意两边的类型,以上几个函数,是在PHP中比较常用的字符串查找函数了,如需更强大功能的话,如邮箱、手机号的匹配、验证的话,则需借助正则表达式完成。

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php常用函数与技巧总结》、《php字符串(string)用法总结》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » php常用字符串查找函数strstr()与strpos()实例分析

转载请保留出处和原文链接:https://www.cnhackhy.com/59378.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部