Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search if a string exists in another string

Tags:

php

for my purposes I did this:

<?php
$mystring = 'Gazole,';
$findme   = 'Sans Plomb 95';
$pos = strpos($mystring, $findme);

if ($pos >= 0) {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
} else {
    echo "The string '$findme' was not found in the string '$mystring'";
}
?>

However, it always executes this branch:

echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";

although the string I 'm searching for doesn't exist.

Please help, thx in advance :))

like image 320
Malloc Avatar asked Apr 25 '11 10:04

Malloc


2 Answers

The correct way to do it is:

if ($pos !== false) {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
} else {
    echo "The string '$findme' was not found in the string '$mystring'";
}

See the giant red warning in the documentation.

like image 163
Jon Avatar answered Oct 10 '22 05:10

Jon


strpos returns a boolean false in case the string was not found. Your test should be $pos !== false rather than $pos >= 0.

Note that the standard comparison operators do not consider the type of the operands, so that false is coerced to 0. The === and !== operators yield true only if the types and the values of the operands match.

like image 37
Blagovest Buyukliev Avatar answered Oct 10 '22 04:10

Blagovest Buyukliev