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?
You could simply do the check for
$casesensonce 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_replaceandstri_replacethat takes an extra boolean argument, to ignore case or not and, call the appropriate string replace function.preg_replaceinstead of the string replace functions just like you previously did and use the same way to solve the problem as I explained above.