1

I have a string like this: $str1 = "mod 1 + mode 2 + comp 1 + toto".

I would like to test if mod 1 is in $str1. I used strpos but this function doesn't help.

1
  • But "mod 1 + mode 2 + comp 1 + toto" really does not contain " mod 1" (note the spaces). Commented Mar 24, 2010 at 14:07

3 Answers 3

5

strpos returns the position of the occurrence in the string starting with 0 or false otherwise. Using just a boolean conversion like in the following is a common mistake:

$str1 = "mod 1 + mode 2 + comp 1 + toto";
if (strpos($str, "mod 1")) {
    // found
}

Because in this case strpos will return 0. But 0 converted to Boolean is false:

var_dump((bool) 0 === false);  // bool(true)

So you need to use a strict comparison:

$str1 = "mod 1 + mode 2 + comp 1 + toto";
if (strpos($str, "mod 1") !== false) {
    // found
}

This is also what the documentation advises:

Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes I see, but the use of this , always return false ! I am gonna try again and will post thank u guys
1

You can make use of the strstr function.

$str1 = "mod 1 + mode 2 + comp 1 + toto";
$str2 = "mod 1";

if(strstr($str1,$str2) !== false)
 echo "Found $str2 in $str1\n";

1 Comment

@Mamadou: This code works, but you should go through Gumbo's answer and try to understand why the strpos you tried did not work.
0
if(stripos($str,'mod 1')!==false) $hasmod1 = true;
else $hasmod1 = false;

Care for the !== this is the important part.

See http://php.net/manual/en/function.stripos.php

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.