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

时间:2022-07-27
本文章向大家介绍php常用字符串查找函数strstr()与strpos()实例分析,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

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

string strstr ( string haystack , mixed needle [, bool

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

<?php
 $email = 'name@example.com';
 $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

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中比较常用的字符串查找函数了,如需更强大功能的话,如邮箱、手机号的匹配、验证的话,则需借助正则表达式完成。