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

2025-05-29 0 93

本文实例讲述了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()函数

?

1

2

3

4

5

6

7

8

9
<?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 $offset = 0 ] )

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

?

1

2

3

4

5

6
<?php

$mystring = 'abc' ;

$findme = 'a' ;

$pos = strpos($mystring,$findme);

echo $pos; //输出0,既是当前a的位置

?>

运行结果:

0

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

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

实例1 使用 ===

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14
<?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 使用 !==

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14
<?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 使用位置偏移量

?

1

2

3

4

5
<?php

// 忽视位置偏移量之前的字符进行查找

$newstring = 'abcdef abcdef';

$pos = strpos($newstring, 'a', 1); // $pos = 7, 不是 0

?>

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

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

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

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

原文链接:https://www.cnblogs.com/jinsanguo/p/7620070.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 php常用字符串查找函数strstr()与strpos()实例分析 https://www.kuaiidc.com/92484.html

相关文章

发表评论
暂无评论