tags:

views:

86

answers:

5

Hi,

I have a viariable that contains something like this ab_123456789

how can i check if the variable starts with ab_?

thanks, sebastian

+5  A: 

Use regular expressions

$var = "ab_123456789";
if(preg_match('/^ab_/', $var, $matches)){
    /*your code here*/
}
cypher
preg_match will return 0 if nothing matches or an integer representing the number of times the match was found.
marduk
(bool)0 === false -> true
cypher
+5  A: 

You can use strpos():

$text = "ab_123456789";
if(strpos($text, "ab_") === 0)
{
    // Passed the test
}
In silico
Note that `strpos` will search until a match is found or the end of the string is reached.
Gumbo
Hmm, good point
R. Hill
A: 

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.

Guillaume Lebourgeois
Strings aren't arrays in PHP.
Daniel Egeberg
@Daniel Egeberg: But strings can be accessed like arrays. See http://php.net/manual/en/language.types.string.php#language.types.string.substr
Gumbo
It's not an Array object, but you can access it as you do for an array.
Guillaume Lebourgeois
@Gumbo: I think Daniel Egeberg means that the answer implies that a string is an array, which it isn't. The part about accessing using array notation is correct though.
BoltClock
+8  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.

Gumbo
A: 

The easiest way would be to get a sub string. e.g. substr('ab_123456789', 0, 3);

George