PHP 判断是否包含在某个字符串中

本文介绍了四种使用PHP来判断一个字符串是否包含特定字符的方法:利用strpos函数查找字符位置;使用strstr函数获取字符出现后的子串;通过explode将字符串分割成数组并检查长度;以及运用in_array函数在数组中搜索特定值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PHP 判断是否包含在某个字符串中

1.用strpos函数,查找字符首次出现的位置,如果不存在则会返回false
$str= ‘abc’;
$needle= ‘e’;
p o s = s t r p o s ( pos = strpos( pos=strpos(str, $needle);
2.用strstr函数查找字符在字符串中首次出现,并返回字符出现开始的位置至结束的字符串
$email = ‘user@example.com’;
d o m a i n = s t r s t r ( domain = strstr( domain=strstr(email, ‘@’);
3.用explode分割字符串,如果返回的数组长度大于一则表示存在
$str= ‘abc’;
$needle = ‘E’;//判断是否包含a这个字符
t m p a r r a y = e x p l o d e ( tmparray = explode( tmparray=explode(needle,$str);
4.用in_array检查数组中是否存在某个值
// bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
//in_array()例子
o s = a r r a y ( " M a c " , " N T " , " I r i x " , " L i n u x " ) ; i f ( i n a r r a y ( " I r i x " , os=array("Mac","NT","Irix","Linux"); if(in_array("Irix", os=array("Mac","NT","Irix","Linux");if(inarray("Irix",os)){
echo “Got Irix”;
}
if(in_array(“mac”,$os)){
echo “Got mac”;
}
//第二个条件失败,因为in_array()是区分大小写的 所以只输出Got Irix
//in_array() 严格类型检查例子
$a = array(‘1.10’, 12.4, 1.13);
if (in_array(‘12.4’, $a, true)) {
echo “‘12.4’ found with strict check\n”;
}
if (in_array(1.13, $a, true)) {
echo “1.13 found with strict check\n”;
}
//程序会输出1.13 found with strict check
//in_array()中数组作为needle
$a = array(array(‘p’, ‘h’), array(‘p’, ‘r’), ‘o’);
if (in_array(array(‘p’, ‘h’), $a)) {
echo “‘ph’ was found\n”;
}
if (in_array(array(‘f’, ‘i’), $a)) {
echo “‘fi’ was found\n”;
}
if (in_array(‘o’, $a)) {
echo “‘o’ was found\n”;
}
//程序会输出
//‘ph’ was found
//‘o’ was found

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值