在字符串中查找文本并在数组中替换

时间:2017-09-14 12:03:29

标签: php arrays multidimensional-array replace

我有一个字符串:

$string = 'I love my kitty and other animals.'; 

$categories = array(
    'kitty' => 'cat',
    'teddy' => 'bear',
    'someting' => 'other',
);

我想创建一个在数组中查找文本并转换它们的函数。 有些像:

function find_animal_in_string($string)
{
    // If $string contains one of the element in array print this array value
    // how to do that?
}

所以我的首选结果是:

echo $this->find_animal_in_string('I love my leon and other animals.') //echo cat
echo $this->find_animal_in_string('I do not like teddys in mountains.') //echo bear

非常感谢您的帮助。我已经尝试过strpos和array_key_exists,但对我没用。

3 个答案:

答案 0 :(得分:1)

您可以使用strpos检查字符串是否存在

foreach($categories as $key => $value){


 if(strpos($string,$key) == true)

    echo $value;


}

答案 1 :(得分:1)

function find_animal_in_string($string)
{
// If $string contains one of the element in array print this array 
// how to do that?
 $categories = array(
'kitty' => 'cat',
'teddy' => 'bear',
'someting' => 'other',
 );
foreach($categories as $cle => $value){
    if(strpos($string,$cle) != FALSE){
    echo $value;
    }
 }
}   

    find_animal_in_string('I do not like teddy in mountains.');//echo bear

答案 2 :(得分:1)

您也可以使用正则表达式执行此操作:

function find_animal_in_string($string)
{
// global $categories
        $matches = "/(".join("|", array_keys($categories)).")/";
        preg_match($matches, $string, $hit);
        return $categories[$hit[0]];
}

不要忘记$ categories的可见性