I'm building an application using CI latest. My problem is that i have a long list of regex like:
$regex1 = "/.../";
$regex2 = "/.../";
...
$regexn = "/.../";
And i need to pass an if statement for every regex like this:
if(preg_match($regex1, $input)){
$data['result'] = $this->Model1->get_text();
}
if(preg_match($regex2, $input)){
$data['result'] = $this->Model2->get_text();
}
...
The thing works but i hate to see all the if's there. And my question is how can i shorten this in any way and make it more maintainable in CI
Use an array to loop through each possibility, Although this example is dependant on the idea that your models are actually named Model1
.. Model2
(Sorry if that was there for just as an Example, otherwise replace the numbered keys to your model names, ModelAdmin => $regex1
etc. )
$Regexes = array(
0 => $regex1,
1 => $regex2,
//etc
);
foreach( $Regexes as $Key => $Regex ) {
if( preg_match( $Regex, $input )) {
$Model = "Model" . $Key;
$data['result'][] = $this->$Model->get_text();
}
}
Furthermore, added an []
at the end of $data['result']
, otherwise it overwrite the previous 'result'