vero
vero

Reputation: 1015

How to check if a string starts with another string - PHP

I want test if a String1 start by a string2 in PHP

I found this question: How to check if a string starts with a specified string

But I want do it inside an if condition - not in a function. I did it like this but I'm not sure:

if(startsWith($type_price,"repair")) {

do something

} 

Can you please correct me if it's false?

Upvotes: 6

Views: 18968

Answers (3)

JSowa
JSowa

Reputation: 10642

As of PHP 8.0 there is method str_starts_with implemented:

if (str_starts_with($type_price, "repair")) {
    //do something
} 

Upvotes: 1

unalignedmemoryaccess
unalignedmemoryaccess

Reputation: 7441

Using strpos function can be achieved.

if (strpos($yourString, "repair") === 0) {
    //Starts with it
}

Using substr can work too:

if (substr($yourstring, 0, strlen($startString)) === $startString) {
    //It starts with desired string
}

For multi-byte strings, consider using functions with mb_ prefix, so mb_substr, mb_strlen, etc.

Upvotes: 25

Phil
Phil

Reputation: 4069

if (substr($string,0,strlen($stringToSearchFor)) == $stringToSearchFor) {
     // the string starts with the string you're looking for
} else {
     // the string does NOT start with the string you're looking for
}

Upvotes: 1

Related Questions