php - 将 PHP 数组值与字符串的一部分进行比较

标签 php arrays substring

我正在尝试自动筛选我的在线银行对账单。这是我需要的一个简单示例。

我有一系列餐厅,我可以根据这些餐厅对信用卡账单进行排序:

$restaurants = array(
    array("vendor" => "default",
            "type" => "default"
    ),
    array("vendor" => "dunkin",
            "type" => "pastry"
    ),
    array("vendor" => "mcdonald",
            "type" => "fastfood"
    ),
    array("vendor" => "olive",
            "type" => "italian"
    )
);

语句条目本身可以是一个相当具有描述性的字符串:

$string = "McDonald's Restaurants Incorporated";

我尝试过使用 array_searchin_array ,但他们似乎做了与我需要的相反的事情,或者他们需要完全匹配,如下例所示,但这不是我需要的:

$result = array_search($string, array_column($restaurants, 'vendor'));
return $restaurants[$result]['type'];

// returns "default" because "McDonald's Restaurants Incorporated" != "mcdonald"

我希望能够将数组值“mcdonald”与包含该 block 的任何字符串相匹配,然后为其返回类型“fastfood”。不用担心处理多次出现的情况。

最佳答案

您需要组合一些东西 - a search-in-string method, and for it to be case insensitive .

您可以通过以下方式完成此操作:

/**
 * Perform a string-in-string match case insensitively
 * @param  string $string
 * @param  array  $restaurants
 * @return string|false
 */
function findRoughly($string, $restaurants)
{
    $out = false;
    foreach ($restaurants as $restaurant) {
        // Set up the default value
        if ($restaurant['type'] == 'default' && !$out) {
            $out = $restaurant['type'];
            // Stop this repetition only
            continue;
        }
        // Look for a match
        if (stripos($string, $restaurant['vendor']) !== false) {
            $out = $restaurant['type'];
            // Match found, stop looking
            break;
        }
    }
    return $out;
}

像这样使用它:

$result = findRoughly("McDonald's", $restaurants);

Example here.

关于php - 将 PHP 数组值与字符串的一部分进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31690724/

相关文章:

mysql - 如何为 MySQL 中的每一行获取可变大小的子字符串?

php - 将MySQL数据合并到同一个列表中

php - 在 php 中使用变量作为关联数组值时出错

php - 如果已经使用 Laravel 作为后端,为什么还要在前端使用 AngularJs?

Java比较int数组,过滤并插入或更新到数据库

Python:有效替换子字符串

php - 更改 CakePHP 中自定义日志的路径

java - 如何查找并返回数组中逐渐最低的值的索引 Java

c# - 如何将字符串字符转换为整数数组

php - 查找字符串中重叠的所有子字符串