Home > Backend Development > PHP Tutorial > 关于两个字符串对比的有关问题,50分

关于两个字符串对比的有关问题,50分

WBOY
Release: 2016-06-13 13:51:19
Original
870 people have browsed it

关于两个字符串对比的问题,50分
在php中有一字符串是
$str1= "45,25,69,54,85,4,2,6,8,41,22,2 ";
$str2= "2 ";或者是以上的任务一个数(,)号是个分隔符的

那这里怎么样写一个有效率有函数对比于$str2是属于$str1的。

我现在写的是

function   testStr($str1,$str2)
{
$tStr=false;
$strArray=explode( ", ",$str1);
foreach($strArray   as   $sa)
{
if($sa==$str2)
{
$tStr=true;
}
}
return   $tStr;
}

要怎么写一个比这个高好的。比如正则表达式呀那就更棒了。请各位指点一下

------解决方案--------------------
函数一.
function testStr($str1,$str2)
{
$tStr=false;
$strArray=explode( ", ",$str1);
if (in_array($str2,$strArray))
{
$tStr = true;
}
return $tStr;
}
函数二.
function testStr2($str1,$str2)
{
$tStr=false;
$pattern = "/^{$str2},|,{$str2}$|,{$str2},/ ";
if (preg_match($pattern,$str1))
{
$tStr = true;
}
return $tStr;
}

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template