Q:

how to check the first three characters in a variable?

I have a viariable that contains something like this ab_123456789
how can i check if the variable starts with ab_?
thanks,
sebastian

A:

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.

A:

Use regular expressions
$var = "ab_123456789";
if(preg_match('/^ab_/', $var, $matches)){
    /*your code here*/
}

A:

You can use strpos():
$text = "ab_123456789";
if(strpos($text, "ab_") === 0)
{
    // Passed the test
}

