【问题标题】:Improving a PHP function改进 PHP 函数
【发布时间】:2016-09-14 12:27:12
【问题描述】:

我正在为异常字符串使用 switch-function,应该为正确的 h1-titles 等进行更改。

我的目标是减少function ausnahme 的异常。

function ausnahme($value) {
    global $value; // now the function ausnahme may change the variable
    switch ($value) {
        case "kern teilchenphysik": $value = "Kern-/Teilchenphysik";
            break;
        case "tipps tricks": $value = "Tipps & Tricks";
            break;
        case "erich honecker": $value = "Erich Honecker";   
            break;
        case "ökogeographische regeln": $value = "Ökogeographische Regeln";
        break;              
    }
    return $value;
}

这个开关现在有 3000 行,我想要函数中这个开关之前的规则。

示例:要删除所有带有 2 个单词或更好的 x-words 的 switch-terms,它们都应该以大写字母开头我想要我的函数 bigwords:

例子:二字->二字,三字-表达->三字表达

有些词不能大写,例如'und'、'das';'der'、'die'等。

function bigwords($value) {
    global $value;
    $value = "X" . $value;
// Hilfsvariable,da & sonst auf Position 0 steht,
// was gleichbedeutend mit FALSE/NULL angesehen wird
    if (strpos($value, "&a") == "1") {
        $value = substr($value, 2);
        $value = "&" . ucfirst($value);
    } elseif (strpos($value, "&o") == "1") {
        $value = substr($value, 2);
        $value = "&" . ucfirst($value);
    } elseif (strpos($value, "&u") == "1") {
        $value = substr($value, 2);
        $value = "&" . ucfirst($value);
    } else {
        // X wieder entfernen
        $value = substr($value, 1);
        $value = ucfirst($value);
    }
} 

我可以在切换之前使用这部分删除许多切换行,因为对于其他一些情况不同或期望出现异常,我会称之为;-)。 另一个问题是德语变音符号:

示例:“oeffnung-boerse-oekologie”现在是:“Öffnung börse ökologie” 我想用function bigwordsfunction umlaute 来实现:'Öffnung Börse Ökologie'。

function umlaute($value) {
    global $value;      // 12.07.14 str_replace changed from eregi_replace/ 22.07.14 mehrere str_replace mit arrays geändert
    $from = ['-', 'ae', 'oe', 'ue', 'Ae', 'Oe', 'Ue'];
    $to = [' ', 'ä', 'ö', 'ü', 'Ä', 'Ö', '&Uuml'];
    $value = mb_strtolower(str_replace($from, $to, $value), 'utf-8');
// ACHTUNG! Dadurch greift die "erster Buchstabe Groß"-Regel nicht mehr, da erster
// "Buchstabe" nun das Kaufmanns-Und ist! -> wird in bigwords ersetzt
}

// 最后 2 个 cmets 可能已过时,因为我认为 bigwords 规则适用于此功能。我以前的程序员在这个函数之后编写脚本的第一个字母是“&”而不是字母。

对于现有的function bigwordsfunction umlaute,请随时提供我的提示 谢谢你的帮助。

【问题讨论】:

  • 您能否为您的开关提供一个示例输入,并告诉我们您想用您的功能实现什么。因为我不明白你的用语:“删除许多开关线”、“x-words”。
  • 那么为什么全局$value 不只是设置为您首先需要的?您正在以任何方式设置它。看看整体架构,尽管您可能想要创建一个可以为您保存所需页面元素的页面类。
  • 请不要将变量传递给函数然后访问它们global。那没有意义。只需传递变量by reference
  • 会建议在参考上传递 $value,如 &$value。这应该意味着您可以摆脱全局。
  • @simon 我知道 global 不应该被使用,但我不知道没有它不同的功能应该如何工作。在我的大 function_inc.php 文件中,function ausnahme 和更多我发现 8times global :-(.

标签: php function switch-statement


【解决方案1】:

如果我理解你的话,这应该可以解决问题:

<?php 

$noUpper = [];
foreach (
    ['und','das','der','die']
    as $k
) $noUpper[$k] = true;
function prettify($inStr){
    global $noUpper;
    $out = [];
    foreach (
        explode(" ", $inStr)
        as $chunk
    ) array_push($out, @ $noUpper[$chunk] ? $chunk : ucfirst($chunk));
    return htmlentities(implode(" ", $out));
};

echo prettify("hello und me no das & der die"); // Sorry: I don't understand German ;-)

// Output: "Hello und Me No das &amp; der die"

对于 html 实体翻译,我使用了现有的 htmlentities() php 函数。

编辑:

带有cmets中提到的修改的新版本:

<?php 

function prettify($inStr){

    static $noUpper;
    if (is_null($noUpper)) { // Messy static trick
        $noUpper = [];
        foreach (
            ['und','das','der','die']
            as $k
        ) $noUpper[$k] = true;
    };

    $out = [];
    foreach (
        explode("-", $inStr)
        as $chunk
    ) array_push($out, @ $noUpper[$chunk] ? $chunk : ucfirst($chunk));
    return htmlentities(implode(" ", $out));
};

echo prettify("hello-und-me-no-das-&-der-die"); // Sorry: I don't understand German ;-)

// Output: "Hello und Me No das &amp; der die"

...并且,作为(良好)基于闭包的实现的一个示例,这将与 javascript 中的实现相同:

"use strict";
var prettify = (function(){
    // Notice, this is only internally visible scope.
    var noUpper = {};
    for (
        let k of ['und','das','der','die']
    ) noUpper[k] = true;
    function htmlentities(str){
        // There is no native php htmlentities() equivalent in javascript.
        // So should implement it or rely on existing implementations in external
        // modules such underscore.
        // I left it empty because it is only for explanatory purposes.
        return str.replace("&", "&amp;"); // (Just to match PHP example...)
    };

    // ...and below function would be the only thing visible (exposed) outside.
    return function prettify_implementation(inStr){
        return htmlentities(inStr
            .split("-")
            .map(function(chunk){
                chunk = chunk.toLowerCase();
                return noUpper[chunk]
                    ? chunk
                    : chunk.substring(0, 1).toUpperCase()
                        +chunk.substring(1)
                ;       
            })  
            .join(" ")
        );  

    };
})();

console.log(prettify("hello-und-me-no-das-&-der-die")); // Sorry: I don't understand German ;-)

// Output: "Hello und Me No das &amp; der die"

【讨论】:

  • 我认为可能是一个可行的解决方案。 2个问题:使用global是一种好方法吗?在哪里放置你的函数,我应该在$value 中重命名$inStr。你的例子不像我的。每个单词都与'-'分开,就像你的例子'hello-und-me-no-das-&-der-die'。请添加示例输出,例如 echo prettify("oeffnung-boerse-und-oekologie");应该有输出:'Öffnung Böerse und Ökologie。也许函数需要某个地方“UTF-8”。
  • Q1:绝对不是!如果您可以选择,即使使用 php 本身也不是一个好主意:-P。我只是没有太多时间,不得不在效率和优雅之间做出选择;-)。或者,您可以在函数内部使用['und' =&gt; true, 'das' =&gt; true, ...] 解决方案,或者简单地将其构建 foreach 移动到内部(但这意味着每次调用它时都要重新构建它)。正确的解决方案是使用闭包。最新的 PHP 版本理论上带有闭包,但我看到的东西在我看来是一团糟(我不确定它是否对此有用......)。
  • ...所以,最后(在 PHP 中)更好的解决方案是依赖(混乱的)静态变量 + if 语句(我会更新我的答案 ;-))。
  • Q2:正如我所说,我写得很快,我无意中错过了你用“-”而不是空格(“-”)分隔的事实。但修复起来就像替换之前的explode(...) 句子中的那个胶水字符串一样简单。作为说明,也可以通过将strtolower() 应用于每个读取的块来使其不区分大小写(我认为它可以避免一些问题给你......)。但为了简洁起见(以及使代码更简洁以更好地解释您所要求的内容),我省略了这一点。
  • 再次感谢您的编辑,但不幸的是我没有对function prettify(&amp;$value){ 进行任何更改,而是更改了第二个$inStr in $value`。我也尝试不使用我的功能,然后没有任何改变。
猜你喜欢
  • 2018-03-26
  • 1970-01-01
  • 2011-09-18
  • 2019-11-03
  • 2010-12-21
  • 2012-11-07
  • 1970-01-01
  • 2013-02-09
  • 2012-03-13
相关资源
最近更新 更多