6

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?

2
  • 1
    You can perform any operation you like in an if statement. So you can just aswell use substr() as in your linked example in your if condition.
    – Xatenev
    Jun 23, 2017 at 12:58
  • PHP 8.0 introduces new methods for this job str_starts_with: stackoverflow.com/a/64160081/7082164
    – JSowa
    Oct 1, 2020 at 17:09

3 Answers 3

23

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.

1
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
}
1

As of PHP 8.0 there is method str_starts_with implemented:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.