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,383
  • 3
  • 18
  • 42
vero
  • 1,005
  • 6
  • 16
  • 29
  • 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

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.

unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40
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
  • 4,029
  • 9
  • 62
  • 107
1

As of PHP 8.0 there is method str_starts_with implemented:

if (str_starts_with($type_price, "repair")) {
    //do something
} 
Jsowa
  • 9,104
  • 5
  • 56
  • 60