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?
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 .
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.
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().
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With