Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 677
vero Avatar asked Jun 23 '17 12:06

vero


People also ask

How do you check if a string is in another string PHP?

Answer: Use the PHP strpos() Function You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .

How do you check if a string starts with a specified string?

The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false . The startsWith() method is case sensitive. See also the endsWith() method.

How do I match a string in PHP?

The strcmp() function compares two strings. Note: The strcmp() function is binary-safe and case-sensitive. Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp().

What is substr in PHP?

substr in PHP is a built-in function used to extract a part of the given string. The function returns the substring specified by the start and length parameter. It is supported by PHP 4 and above. Let us see how we can use substr() to cut a portion of the string.


1 Answers

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.

like image 149
tilz0R Avatar answered Oct 21 '22 05:10

tilz0R