比嵌套 if-else 更好的解决方案?
不知道如何用更好的标题来描述这一点,但是这是我的问题:
我有一个带有多个布尔选项的替换函数:
- 正则表达式
- 整个单词(仅当正则表达式== false时)
- 区分大小写
,这意味着我必须选择4中的1替换我的文本的方法。目前我的代码如下所示:
(这里的这些选项确实是 true/false 作为字符串,通过 POST 从一组 jquery 复选框)
if($regex=='true')
{
if($casesens=='true')
{
$p->aData['body'] = preg_replace('/'.$q.'/', $r, $p->aData['body']);
}
else
{
$p->aData['body'] = preg_replace('/'.$q.'/i', $r, $p->aData['body']);
}
}
else
{
if($wwords=='true')
{
$q = " ".$q." ";
$r = " ".$r." ";
}
if($casesens=='true')
{
$p->aData['body'] = str_replace($q, $r, $p->aData['body']);
}
else
{
$p->aData['body'] = str_ireplace($q, $r, $p->aData['body']);
}
}
如您所见,如果必须在两种条件下比较 $casesens
,如果我必须添加更多选项,这会变得越来越复杂到用户界面。 有没有更好或更优雅的方式来写这个?
Not sure how this describe this with a better title, however here is my problem:
i have a replace function with multiple boolean options:
- regex
- whole words (only when regex==false)
- case sensitive
and this means i have to choose 1 of 4 ways to replace my text. Currently my code looks like this:
(those options here are indeed true/false as a string, passed in via POST from a set of jquery checkboxes)
if($regex=='true')
{
if($casesens=='true')
{
$p->aData['body'] = preg_replace('/'.$q.'/', $r, $p->aData['body']);
}
else
{
$p->aData['body'] = preg_replace('/'.$q.'/i', $r, $p->aData['body']);
}
}
else
{
if($wwords=='true')
{
$q = " ".$q." ";
$r = " ".$r." ";
}
if($casesens=='true')
{
$p->aData['body'] = str_replace($q, $r, $p->aData['body']);
}
else
{
$p->aData['body'] = str_ireplace($q, $r, $p->aData['body']);
}
}
as you can see, if have to compare $casesens
in both conditons, and this becomes increasingly complex if i have to add more options to the UI.
Is there a better or more elegant way to write this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,您当然可以通过减少大量不必要的重复来简化您所拥有的内容,例如:
我不会称其为优雅,但至少它更短。
Well you can certainly simplify what you have by cutting down a lot of unnecessary duplication, something like:
I wouldn't call that elegant, but at least it's shorter.
您可以简单地检查
$casesens
一次并定义一个如下所示的变量:然后像任何其他变量一样在正则表达式模式中使用它:
这将解决第一个
if
。至于第二种,我可以想到两种方法:str_replace
和stri_replace
的函数,它需要一个额外的布尔参数,以忽略大小写,然后调用适当的字符串替换功能。preg_replace
而不是字符串替换函数,并使用与我上面解释的相同的方法来解决问题。You could simply do the check for
$casesens
once and define a variable like this:And then use it in the regex pattern just like any other variable:
This would solve the first
if
. As for the second one I can think of 2 ways:str_replace
andstri_replace
that takes an extra boolean argument, to ignore case or not and, call the appropriate string replace function.preg_replace
instead of the string replace functions just like you previously did and use the same way to solve the problem as I explained above.您可以使用 PHP 三元运算符来降低复杂性
http://davidwalsh.name/ php-shorthand-if-else-三元运算符
You can use the PHP Ternary Operators to reduce the complexity
http://davidwalsh.name/php-shorthand-if-else-ternary-operators