博主辛苦了,我要打赏银两给博主,犒劳犒劳站长。
【摘要】无论是刚刚接触 PHP ,还是在 PHP 开发多年的人员一定会经常遇到这么一个问题:如何判断字符串中是否包含另外一个字符串?这个问题非常常见,所有应该把它详细记录下来。本文讲讲最准确的方法:使用 strpos()/stripos() 函数来解决这一问题。
strpos():查找子字符串在另外一个字符串中首次出现的位置
stripos():查找子字符串在另外一个字符串中首次出现的位置(不区分大小写)
strpos($string,$substr,$start):
$string -> 被搜索的字符串
$substr -> 要查找的子字符串
#start -> 在 $string 中开始搜索的位置
例如查询在 'http://www.mafutian.net' 中搜索是否存在 'http://' 或者 'https://',则准确的代码如下:
header('content-type:text/html;charset=utf-8');
$string = 'http://www.mafutian.net';
$find1 = 'http://';
$find2 = 'https://';
in_string($string,$find1);
echo '<br />';
in_string($string,$find2);
echo '<br />';
in_string2($string,$find1);
echo '<br />';
in_string2($string,$find2);
echo '<br />';
function in_string($string,$find)
{
if(strpos($string,$find) === false) // 不存在
{
echo $find.' 不在 '.$string.' 中';
}else
{
echo $find.' 在 '.$string.' 中';
}
}
// 或者使用另外一种方式
function in_string2($string,$find)
{
if(strpos($string,$find) !== false) // 存在
{
echo $find.' 在 '.$string.' 中';
}else
{
echo $find.' 不在 '.$string.' 中';
}
}
执行结果如下图所示:
需要注意的是字符串位置起始是 0 不是 1,因此如果没有发现,则返回 false。以上使用 '!==' 和 '===' 两种方式都是可以的。使用 PHP 判断字符串中是否含有某一子字符串的正确方式应该是以上所述的方法。当然 stripos() 是一样的,区别就在于 stripos() 是不区分大小写的,而 strpos() 是区分大小写的。
版权归 马富天个人博客 所有
本文标题:《PHP 使用 strpos() 函数来判断字符串中是否包含有某一字符串》
本文链接地址:http://www.mafutian.com/312.html
转载请务必注明出处,小生将不胜感激,谢谢! 喜欢本文或觉得本文对您有帮助,请分享给您的朋友 ^_^
顶0
踩0
评论审核未开启 |
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
||