Search if a row exists in another row

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 line I'm looking for does not exist.

Please help, thanks in advance :))

+5
source share
7 answers

The correct way to do this 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.

+14
source

strpos returns boolean false if the string is not found. Your test should be $pos !== false , not $pos >= 0 .

Note that standard comparison operators do not consider the type of operands, so false forced to 0 . The operators === and !== give true only if the types and values โ€‹โ€‹of the operands match.

+3
source

See warning on page

You need to also check if $pos !== false

+1
source

strpos () returns FALSE if the string is not found. When you check $ pos> = 0, you click on this value FALSE.

Try the following:

 <?php $mystring = 'Gazole,'; $findme = 'Sans Plomb 95'; $pos = strpos($mystring, $findme); 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'"; } ?> 
+1
source

hi mank strpos method in php will return the boolean false when the string is not found, and if it is found, it will return the position to int.

link to this link to learn about strpos

+1
source
 if (strpos($mystring, $findme) !== false) { echo 'true'; } 
0
source

A completely different way to do this without worrying about indexes:

 if (str_replace($strToSearchFor, '', $strToSearchIn) <> $strToSearchIn) { //strToSearchFor is found inside strToSearchIn 

What you are doing is replacing any occurrence of the substring and checking if the result matches the original string.

0
source

Source: https://habr.com/ru/post/886615/


All Articles