2017-09-14 134 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