如何循环字符串的字符?

时间:2013-07-20 14:44:10

标签: php string

基本上,我有一个字符串数组,我想检查每个字符串中的每个字符是否都在预定义的$source字符串中。以下是我认为应该如何做的事情:

$source = "abcdef";
foreach($array as $key => $value) {
    foreach(char in $value) {
        if(char is not in source)
            unset($array[$key]); //remove the value from array
    }
}

如果这是正确的逻辑,如何实施foreachif部分?

5 个答案:

答案 0 :(得分:1)

你可以试试这个:

$array = array('1' => 'cab', '2' => 'bad', '3' => 'zoo');
$source = "abcdef";
foreach($array as $key => $value) {
    $split = str_split($value);
    foreach($split as $char){
        $pos = strrpos($source, $char);
        if ($pos === false) {
            unset($array[$key]);
            break;
        }
    }
}

结果:

array(2) {
  [1]=>
  string(3) "cab"
  [2]=>
  string(3) "bad"
}

DEMO:http://codepad.org/fU99Gdtd

答案 1 :(得分:0)

试试这段代码:

$source = "abcdef";
foreach($array as $key => $value) {
  $ichr = strlen($value) - 1;
  // traverses each character in string
  for($i=0; $i<$ichr; $i++) {
    if(stristr($value{$i}) === false) {
      unset($array[$key]);
      break;
      }
    }
}

答案 2 :(得分:0)

$array = array("abc","defg","asd","ade","de","fe");
$source = "abcde";
foreach ($array as $key => $string){
  for($i=0;$i<strlen($string);$i++){
    if(strpos($source, $string[$i])===false){
       unset($array[$key]);
   }
  } 
}

现在数组看起来像

array(3) {
  [0]=>
  string(3) "abc"
  [3]=>
  string(3) "ade"
  [4]=>
  string(2) "de"
}

答案 3 :(得分:0)

据我所知,您希望过滤(删除)$ source变量中未定义的字符。马克贝克评论说,这就是你所需要的:

$source = str_split ( "abdef" );    //defined characters
$target = str_split ( "atyutyu" );  //string to be filtered

$result = array_intersect ( $target, $source );
echo implode( $result );    // output will be only "a"

完整的例子:

$source = str_split ( "abdef" );
$txts = array ( "alfa", "bravo", "charlie", "delta" );

function filter ( $toBeChecked, $against )
{
    $target = str_split ( $toBeChecked );
    return implode ( array_intersect ( $target, $against ) );
}
foreach ( $txts as &$value )
{
    $value = filter ( $value, $source );
}
foreach ( $txts as $value )
{
    echo $value . ", ";
}
//output afa, ba, ae, ae

答案 4 :(得分:0)

$array = array(
    'abacab',
    'baccarat',
    'bejazzle',
    'barcode',
    'zyx',
);


$source = "abcde";
$sourceArray = str_split($source);

foreach($array as $value) {
    $matches = array_intersect($sourceArray, str_split($value));
    echo $value;
    if (count($matches) == 0) {
        echo ' contains none of the characters ', $source, PHP_EOL;
    } elseif (count($matches) == count($sourceArray)) {
        echo ' contains all of the characters ', $source, PHP_EOL;
    } else {
        echo ' contains ', count($matches), ' of the characters ', $source, ' (', implode($matches), ')', PHP_EOL;
    }
}

给出

abacab contains 3 of the characters abcde (abc)
baccarat contains 3 of the characters abcde (abc)
bejazzle contains 3 of the characters abcde (abe)
barcode contains all of the characters abcde
zyx contains none of the characters abcde