Hi,
I have a viariable that contains something like this ab_123456789
how can i check if the variable starts with ab_?
thanks, sebastian
Hi,
I have a viariable that contains something like this ab_123456789
how can i check if the variable starts with ab_?
thanks, sebastian
Use regular expressions
$var = "ab_123456789";
if(preg_match('/^ab_/', $var, $matches)){
/*your code here*/
}
Hey !
It's quite essy, as your string is in fact an array of chars. So you juste have to do something like :
if ($var[0] == "a" && $var[1] == "b" && $var[2] == "c")
return true
You also could use a find function from php library.
Another way using substr:
if (substr('ab_123456789', 0, 3) === 'ab_')
Here substr is used to take the first 3 bytes starting at position 0 as a string that is then compared to 'ab_'. If you want to add case-insensivity, use strcasecmp.
Edit To make the use more comfortable, you could use the following startsWith function:
function startsWith($str, $prefix, $case_sensitivity=false) {
if ($case_sensitivity) {
return substr($str, 0, strlen($prefix)) === $prefix;
} else {
return strcasecmp(substr($str, 0, strlen($prefix)), $prefix) === 0;
}
}
Note that these functions do not support multi-byte characters as only bytes are compared. An equivalent function with multi-byte support could look like this:
function mb_startsWith($str, $prefix, $case_sensitivity=false) {
if ($case_sensitivity) {
return mb_substr($str, 0, mb_strlen($prefix)) === $prefix;
} else {
return mb_strtolower(mb_substr($str, 0, mb_strlen($prefix))) === mb_strtolower($prefix);
}
}
Here the character encoding of both strings is assumed to be the internal character encoding.
The easiest way would be to get a sub string. e.g. substr('ab_123456789', 0, 3);