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?

Xatenev
  • 6,274
  • 3
  • 16
  • 42
vero
  • 935
  • 4
  • 14
  • 27
  • 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 '17 at 12:58
  • PHP 8.0 introduces new methods for this job `str_starts_with`: https://stackoverflow.com/a/64160081/7082164 – Jsowa Oct 01 '20 at 17:09

3 Answers3

22

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.

tilz0R
  • 6,949
  • 2
  • 21
  • 37
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
}
Phil
  • 3,917
  • 7
  • 56
  • 100
1

As of PHP 8.0 there is method str_starts_with implemented:

if (str_starts_with($type_price, "repair")) {
    //do something
} 
Jsowa
  • 6,668
  • 4
  • 37
  • 49