我有这个主要的刺痛。
S,SR,DSR,DS,FX,FXS,SR,DS,S,SR,DS,FX,S,SR,DS,FX,FXS
我希望找到以下每个字符串..
DSR
和FXS
我尝试过以下代码,但它无法给我完美的结果。
...代码
<?php
$mainstring ="S,SR,DSR,DS,FX,FXS,SR,DS,S,SR,DS,FX,S,SR,DS,FX,FXS";
$needed = "DSR,FXS";
if( strpos( $mainstring, $needed ) !== false ) {
echo "Found";
}else{
echo "Not match";
}
?>
答案 0 :(得分:5)
一种解决方案是用逗号分解这些字符串,并验证结果数组的交集计数是否与搜索相同:
$mainstring ="S,SR,DSR,DS,FX,FXS,SR,DS,S,SR,DS,FX,S,SR,DS,FX,FXS";
$needed = "DSR,FXS";
$mainStringArr = explode(',', $mainstring);
$neededArr = explode(',', $needed);
if (count(array_unique(array_intersect($mainStringArr, $neededArr))) == count($neededArr)) {
echo 'found';
} else {
echo 'not found';
}
答案 1 :(得分:0)
按命令分解$needed
字符串并遍历数组,并使用$mainstring
函数将数组的每个值与strpos()
进行比较。如果找到,则将该值放入$arrResut
,其中包含“找到”或“未找到”值,最后打印$arrResult
以查看找到的$需要的值,哪个值不是。
另外,如果找到值,我们会增加$cntNeeded
变量。在foreach
循环比较结束$cntNeeded
&amp; $arrNeeded
是相同的,然后所有值都会被$mainstring
找到,否则不会。
$mainstring ="S,SR,DSR,DS,FX,FXS,SR,DS,S,SR,DS,FX,S,SR,DS,FX,FXS";
$needed = "DSR,FXS";
$arrNeeded = explode(",", $needed);
$arrResult = array();
$cntNeeded = 0;
foreach($arrNeeded as $index => $needed) {
if( strpos( $mainstring, $needed ) !== false ) {
$arrResult[$needed] = "Found";
$cntNeeded++;
}
else{
$arrResult[$needed] = "Not match";
}
}
print("<pre> :: arrResult ::");
print_r($arrResult);
print("</pre>");
if($cntNeeded == count($arrNeeded)) {
echo "Found";
}
else {
echo "Not match";
}