2017-09-14 139 views
-4

代替我有一个字符串:查找字符串文本和阵列

$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,但没有为我工作。

+0

这里有什么问题? – Calimero

+0

如何制作打印结果的功能? – Tikky

+0

做功能,打印结果?你有尝试过什么吗? – Calimero

回答

1

可以使用strpos检查字符串的存在与否

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


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

    echo $value; 


} 
+0

失败,因为您无法在数组中找到'leon',并且在'teddys'和'teddy'之间的比较中失败。虽然,如果OP有一个很好的数组0123',那么这个解决方案将工作 – IsThisJavascript

+0

工作后,我已经cahnged“==真”到“!== false”。 Thx贡献 – Tikky

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 
+0

您可以传递'global $ categories'来让数组超出函数范围。然而,这个失败了,因为OP提供的例子是'teddys'不是'teddy',并且这不会通过OP的第一个例子'leon' – IsThisJavascript

+0

他必须在数组$ category中添加leon和teddys。只是一个例子 –

+0

谢谢,我已经改变了“!= FALSE”为“!== FALSE”,以确保它也可以用于第一个元素 – Tikky

1

你也可以做到这一点与正则表达式:

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

而且不要忘记$的知名度类别

+0

这是有趣的解决方案 - 谢谢 – Tikky