如何删除变量的字符串,如果在数组中检查后,它与数组键不匹配?

时间:2017-12-15 01:24:47

标签: php arrays replace

如何从字符串中删除未出现在数组中的单词实例?

$myVar = "my sisteralannis is not that blonde, here is a goodplace";
$myWords=array(
    array("is","é"),
    array("on","no"),
    array("that","aquela"),
    array("sister","irmã"), 
    array("my","minha"),
    array("myth","mito"),
    array("not","não"),
    array("he","ele"),
    array("good","bom"),
    array("place","lugar"),
    array("here","aqui"),
    array("ace","perito")
); 

echo $myVar;

字符'sisteralannis''goodplace'$myWords数组中不存在,应该从字符串中删除。

预期输出: my is not that, here is

2 个答案:

答案 0 :(得分:2)

尝试爆炸该变量,并检查循环是否匹配 试试这个例子:

$myVar = "my sisteralannis is not that blonde, here is a goodplace";

$myWords=array(
        array("is","é"),
        array("on","no"),
        array("that","aquela"),
        array("sister","irmã"), 
        array("my","minha"),
        array("myth","mito"),
        array("not","não"),
        array("he","ele"),
        array("good","bom"),
        array("place","lugar"),
        array("here","aqui"),
        array("ace","perito")
    );

$words = explode(" ",$myVar);

foreach($myWords as $w){
    $words = array_diff($words,$w);
}

$words = array_diff(explode(" ",$myVar),$words);

echo implode(" ",$words);

输出:

my is not that here is

答案 1 :(得分:1)

请参阅下面的代码。我添加了一个函数inspect_data()来修剪数据,并添加了一个名为exclude_characters()的函数来考虑您不希望包含在数据比较中的字符。



<?php 

function inspect_data($text, $array){
    $data = '';
    foreach($array as $myWord){
        if(in_array($text,$myWord)){            
            $data=$text;
        }

    }
    return $data;
}

function exclude_characters($text){

    $excluded_characters = array(',','!');

    $data['string'] = '';
    $data['special'] = '';
    foreach($excluded_characters as $char){
        if (strpos($text, $char) !== false) {
            $data['string'] = str_replace($char,"",$text);
            $data['special'] = $char;
        }
        else{
             $data['string'] = $text;
          
        }
    }
    return $data;
}

$myVar = "my sisteralannis is not that blonde, here is a goodplace";
    $myWords=array(
        array("is","é"),
        array("on","no"),
        array("that","aquela"),
        array("sister","irmã"), 
        array("my","minha"),
        array("myth","mito"),
        array("not","não"),
        array("he","ele"),
        array("good","bom"),
        array("place","lugar"),
        array("here","aqui"),
        array("ace","perito")
    ); 

$newVar = '';
$var = explode(" ",$myVar);
foreach($var as $v){
    
    $data = exclude_characters($v);
    $newVar .= inspect_data($data['string'],$myWords).$data['special']." ";
    
}
echo $newVar;






 ?>
&#13;
&#13;
&#13;