In case you'd like to compare/benchmark the regex technique, it will look like this:
Code: (Demo)
$params = "colorgroup-b;test;abc";
var_dump(array_includes("colorgroup", $params)); //outputs: colorgroup-b
function array_includes($needle, $params) {
return preg_match('/[^;]*' . preg_quote($needle, '/') . '[^;]*/', $params, $m) ? $m[0] : false;
}
For small scale execution, no user is going to notice any performance differences.
For large scale executions, there may actually be some advantage in this way because a full length array doesn't need to be generated to begin the searching. Notice that there will potentially be n calls of strpos()
.
There is also the versatility of this script. It doesn't take much effort to modify the script to extract multiple matches. Or use case-insensitivity. Or multibyte awareness. Or employ word boundaries (something that non-regex techniques struggle to do simply). These adjustments are so slight that if you wanted individual command over all of the above options, you wouldn't need a separate method for each - just pass additional parameters to the method.
function stringSearch($needle, $params, $singleMatch = true, $caseInsensitive = false, $multibyte = false, $wordBoundaries = 'neither') {
(I am thinking wordBoundaries might be neither
, left
, right
, or both
.)
Returning an array is as easy as adding four-characters to preg_match
to become preg_match_all
. Demo
This might also be a timely opportunity to bring up Premature Optimization. Assuming the input string in your application is expected to be a length of tens-of-characters and it is not called thousands of times in an iterative process, the processing time from KIKO's snippet versus my snippet will be entirely unnoticeable.
With that criteria mostly written off as moot, other criteria can be mentioned.
If the idea of regular expressions sends shivers down the spine of you or your development team, that is a perfectly valid justification to use KIKO's technique.
If your code base already contains simple regular expression techniques like my snippet, then my snippet will conform nicely to the project.
I personally never shy away from the convenience that regex affords. I also value the directness and conciseness whenever performance is not noticeably impacted. If a non-regex technique would provide a more brief, direct process, I would opt for that. (Just my opinion of course)
p.s. if your $needle
value is already sufficiently sanitized, the preg_quote
call may be omittable.
"colorgroup-a;colorgroup-b;test;abc"
and why? \$\endgroup\$