如何在主字符串中找到多个逗号分隔的字符串

时间:2016-10-27 12:19:01

标签: php string

我有这个主要的刺痛。

S,SR,DSR,DS,FX,FXS,SR,DS,S,SR,DS,FX,S,SR,DS,FX,FXS

我希望找到以下每个字符串..

DSRFXS

我尝试过以下代码,但它无法给我完美的结果。

...代码

<?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";
    }
?>

2 个答案:

答案 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";
}