Home  >  Article  >  Backend Development  >  判断数组值在字符串中出现的顺序

判断数组值在字符串中出现的顺序

WBOY
WBOYOriginal
2016-06-13 12:16:12895browse

求一个判断数组值在字符串中出现的顺序
数组
$arr=array('A','M','N');
字符串不定,但是M和N在字符串中只能出现一次,如果出现多次则返回false
符合要求则返回数组$data['M'],$data['N']
比如:
A MAN  返回 2,4   //M为数组中第2个出现,N为数组中第4个出现 (A出现在1和3)
A BOY 返回 false //不含M或者N
MAN 返回1,3   //M为数组中第1个出现,N为数组中第3个出现 (A出现在2)
A ATM IN 返回 3,5   //M为数组中第3个出现,N为数组中第4个出现 (A出现在1和2)

------解决思路----------------------
本来一个简单的问题,被你已解释变得复杂了
开看这段代码的结果就知道该怎么做了

$arr = array('A','M','N');<br /><br />$data = array(<br />  'A MAN',<br />  'A BOY',<br />  'MAN',<br />  'A ATM IN'<br />);<br /><br />foreach($data as $text) {<br />  $t = str_split($text);<br />  $r[] = array_intersect($t, $arr);<br />}<br />print_r($r);
Array<br />(<br />    [0] => Array<br />        (<br />            [0] => A<br />            [2] => M<br />            [3] => A<br />            [4] => N<br />        )<br /><br />    [1] => Array<br />        (<br />            [0] => A<br />        )<br /><br />    [2] => Array<br />        (<br />            [0] => M<br />            [1] => A<br />            [2] => N<br />        )<br /><br />    [3] => Array<br />        (<br />            [0] => A<br />            [2] => A<br />            [4] => M<br />            [7] => N<br />        )<br /><br />)<br /><br />

------解决思路----------------------
$arr = array('A','M','N');
$str = 'AMN';
$data = array();
foreach($arr as $v){
if(substr_count($str,$v) == 1){
$data[$v] = strpos($str,$v);
}
}
var_dump($data);

Statement:
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