Better solution than nested if-else?
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 loo开发者_如何学Pythonks 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?
Well you can certainly simplify what you have by cutting down a lot of unnecessary duplication, something like:
if(!$regex) $q = preg_quote($q);
elseif($words) $q = "\s{$q}\s/";
$q = "/{$q}/";
if($casesens) $q .= 'i';
$p->aData['body'] = preg_replace($q, $r, $p->aData['body']);
I wouldn't call that elegant, but at least it's shorter.
You could simply do the check for $casesens
once and define a variable like this:
if($casesens=='true') {
$case = 'i';
}
And then use it in the regex pattern just like any other variable:
$p->aData['body'] = preg_replace('/'.$q.'/'.$case, $r, $p->aData['body']);
This would solve the first if
. As for the second one I can think of 2 ways:
- Create a function similar to
str_replace
andstri_replace
that takes an extra boolean argument, to ignore case or not and, call the appropriate string replace function. - You could use
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.
You can use the PHP Ternary Operators to reduce the complexity
http://davidwalsh.name/php-shorthand-if-else-ternary-operators
精彩评论