php中判断一个字符是否在字符串中
php中判断一个字符是否在字符串中 下面介绍使用方法:
strstr: 返回一个从被判断字符开始到结束的字符串,如果没有返回值,则不包含 代码如下:
1
2
3
4
5
6<?php
/*如手册上的举例*/
$email = 'user@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
?>stristr: 它和strstr的使用方法完全一样.唯一的区别是stristr不区分大小写.
用explode进行判断 代码如下:
1
2
3
4
5
6
7
8
9function checkstr($str){
$needle = "a";//判断是否包含a这个字符
$tmparray = explode($needle,$str);
if(count($tmparray)>1){
return true;
} else{
return false;
}
}strpos: 返回boolean值.FALSE和TRUE不用多说.用 “===”进行判断.strpos在执行速度上都比以上两个函数快,另外strpos有一个参数指定判断的位置,但是默认为空.意思是判断整个字符串.缺点是对中文的支持不好.使用方法
strpos() - 查找字符串在另一字符串中第一次出现的位置(区分大小写)
stripos() - 查找字符串在另一字符串中第一次出现的位置(不区分大小写)
strrpos() - 查找字符串在另一字符串中最后一次出现的位置(区分大小写)
strripos() - 查找字符串在另一字符串中最后一次出现的位置(不区分大小写)
参数: strripos(string,find,start) string:必需。规定要搜索的字符串。 find:必需。规定要查找的字符。 start:可选。规定开始搜索的位置。
例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
141#
<?php
$str = 'abcdef';
$find = 'abc';
$pos = strpos($mystring, $findme);
// 注意这里使用的是 ===不能使用==
// 因为如果没有字符串 就返回false,如果这个字符串位于字符串的开始的地方,
就会返回0为了区分0和false就必须使用等同操作符 === 或者 !==
if ($pos === false) {
echo "$find不在$str中";
} else {
echo "$find在$str中";
}
?>1
22#
- Title: php中判断一个字符是否在字符串中
- Author: algorain
- Created at: 2017-04-30 22:19:15
- Updated at: 2023-05-14 21:39:50
- Link: http://www.rain1024.com/2017/04/30/php-article78/
- License: This work is licensed under CC BY-NC-SA 4.0.
Comments