tags:

views:

59

answers:

3

Hi everybody I got a string like this : $str1 = "mod 1 + mode 2 + comp 1 + toto" I would like to test even " mod 1" is in $str1. I used strpos but this function dosen't help

Pliz can anyone give an idea to fix this problem

thank u.

+1  A: 

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";
codaddict
that's wonderful, !!
Mamadou
@Mamadou: This code works, but you should go through `Gumbo's` answer and try to understand why the `strpos` you tried did not work.
codaddict
A: 
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

Mannaz
+5  A: 

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.

Gumbo
Yes I see, but the use of this , always return false ! I am gonna try again and will postthank u guys
Mamadou