当我使用开关时,为什么我的功能不起作用?

时间:2017-10-19 10:43:41

标签: php function switch-statement constants

我的功能是删除少于2个字符的单词。第一个版本正在运行:

function delLess2($array, $less){
    $english = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
    return preg_grep('~\A[^'.$english.']{'.$less.',}\z~u', $array);
}

使用功能:

$words = array("ӯ","ӯро","ӯт","ғариб","афтода","даст", "ра");

delLess($words, 3);

// Output
Array
(
    [1] => ӯро
    [3] => ғариб
    [4] => афтода
    [5] => даст
)

但是这个更新版本不起作用:

function delLess(&$array, $less = 0, $lang = FALSE)
{
    $english = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
    $russian = "ёйцукенгшщзхъфывапролджэячсмитьбюЁЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ";

    define(ENGLISH, $english);
    define(RUSSIAN, $russian);

    switch ($lang) 
    {
        case ENGLISH:
            return preg_grep('~\A[^'.ENGLISH.']{'.$less.',}\z~u', $array);
            break;

        case RUSSIAN:
            return preg_grep('~\A[^'.RUSSIAN.']{'.$less.',}\z~u', $array);
            break;

        default:
            return false;       
    }   
}

代码中的哪个地方有错误?怎么纠正?

2 个答案:

答案 0 :(得分:1)

设置默认语言,摆脱常数。

<?php

$words = array("ӯ","ӯро","ӯт","ғариб","афтода","даст", "ра");

function delLess(&$array, $less = 0, $lang = 'ru')
{
    $english = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
    $russian = "ёйцукенгшщзхъфывапролджэячсмитьбюЁЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ";

    switch ($lang) 
    {
        case 'en':
            return preg_grep('~\A[^'.$english.']{'.$less.',}\z~u', $array);
            break;

        case 'ru':
            return preg_grep('~\A[^'.$russian.']{'.$less.',}\z~u', $array);
            break;

        default: 
            throw new Exception('unsupported language');      
    }   
}

var_dump(delLess($words, 3, 'en'));

哪个给你:

array(4) { [1]=> string(6) "ӯро" [3]=> string(10) "ғариб" [4]=> string(12) "афтода" [5]=> string(8) "даст" } 

请在此处查看:https://3v4l.org/d5BYR

答案 1 :(得分:1)

使用switch时,PHP会尝试将变量($lang)与case子句中的一个匹配。由于您已将这些字段定义为您要使用的字母而不是该语言的代码,因此它不会匹配任何字段。

另一种更具可扩展性的解决方案是使用语言代码的关联数组和用于该代码的字母...

<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );

$words = array("ӯ","ӯро","ӯт","ғариб","афтода","даст", "ра");

function delLess(&$array, $less = 0, $lang = 'en')
{
    $trans = ["en" => "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM",
            "ru" => "ёйцукенгшщзхъфывапролджэячсмитьбюЁЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ"
    ];

    if ( isset($trans[$lang]))  {
        return preg_grep('~\A[^'.$trans[$lang].']{'.$less.',}\z~u', $array);
    }
    else    {
        return false;
    }
}

$test = delLess($words, 3, 'en');
print_r($test);