【问题标题】:Find text in string and replace in array在字符串中查找文本并在数组中替换
【发布时间】:2018-02-23 09:49:35
【问题描述】:

我有一个字符串:

$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 但对我不起作用。

【问题讨论】:

  • 这里有什么问题?
  • 如何制作一个打印结果的函数?
  • 创建一个函数,打印结果?你试过什么吗?
  • 你必须用 cat ryt 替换 leon?
  • leon 不起作用,因为它不在您的 $categories 数组中。你的第二个例子有teddys,但在你的数组中你有teddy。 Stackoverflow 不是免费的编码服务,我们将在其中开发复杂的语言算法。我们在这里帮助您解决您可能遇到的具体问题

标签: php arrays multidimensional-array replace


【解决方案1】:

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

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


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

    echo $value;


}

【讨论】:

  • 失败,因为您在数组中找不到leon,并且在teddys 和teddy 之间的比较中失败。虽然,如果 OP 有一个不错的数组,这个解决方案会起作用
  • 在我将“== true”更改为“!== false”后工作。感谢贡献
【解决方案2】:
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

【讨论】:

  • 您可以通过global $categories 将数组移出函数范围。但是,这失败了,因为 OP 提供的示例是 teddys 而不是 teddy 并且这没有通过 OP 的第一个示例 leon
  • 他必须在数组 $categories 中添加 leon 和 teddys。只是一个例子
  • 谢谢,我只将 "!= FALSE" 更改为 "!== FALSE" 以确保它也适用于第一个元素
【解决方案3】:

您也可以使用正则表达式来做到这一点:

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

别忘了 $categories 的可见性

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多