Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check the first three characters in a variable?

Tags:

php

I have a viariable that contains something like this ab_123456789

how can i check if the variable starts with ab_?

thanks, sebastian

like image 968
sebastian Avatar asked Jul 19 '10 16:07

sebastian


3 Answers

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.

like image 105
Gumbo Avatar answered Oct 17 '22 08:10

Gumbo


Use regular expressions

$var = "ab_123456789";
if(preg_match('/^ab_/', $var, $matches)){
    /*your code here*/
}
like image 25
cypher Avatar answered Oct 17 '22 07:10

cypher


You can use strpos():

$text = "ab_123456789";
if(strpos($text, "ab_") === 0)
{
    // Passed the test
}
like image 6
In silico Avatar answered Oct 17 '22 07:10

In silico