I want to compare the prefix of two strings to know if both are the same or different. Like if the format is the same.
Assume variable A contains a string with a prefix, i want to compare if the prefix of the value of variable A is the same with a string ie if($variableA == "che-123456")
do something else do something else. The prefix CHE
is what i want to compare.
I have written universal function for your question. You can use it :
function comparePrefixes($a, $b, $separator = "-", $caseSensitive = false) {
if (!$caseSensitive) {
$a = strtolower($a);
$b = strtolower($b);
}
return substr($a, 0, strpos($a, $separator)) === substr($b, 0, strpos($b, $separator));
}
// Testcases
var_dump(comparePrefixes('chE-454545', 'ChE-78623')); //true
var_dump(comparePrefixes('chE.54545', 'ChE.78623', ".")); //true
var_dump(comparePrefixes('abcd-454545', 'abcd-78623')); //true
var_dump(comparePrefixes('chE-454545', 'ChE-78623', "-", true)); //false
var_dump(comparePrefixes('che-454545', 'che-78623', "-", true)); //true
// use case
$a = "che-1234";
$b = "che-5425";
if (comparePrefixes($a, $b)) {
echo "prefixes are equal";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.