Search code examples
phpstrpos

How to check if a string contains an exact substring in Php


I am trying to check if a number say 1 is present in a string say 11,12,13 To do this I am using strpos:

<?
$s = "2,3,11,12,13";
$ss = "1";
if(strpos($s, $ss)) echo "success";
else echo "fail";
?>

Here I am expecting the code to give fail as output but it gives success. Is there any function I can use to exactly match the number in a string. I want the number 1 in the string, not the numbers containing 1 like 11,123,100 etc.

Edit 1: It works fine for @Twinfriends answer but the problem is doing it with multiple numbers.

<?
    $s = "2,3,11,12,13";
    $ss = "1,2";
    if(strpos($s, $ss)) echo "success";
    else echo "fail";
    ?>

This code gives output fail but it should give true.

Edit 2: Check answer https://stackoverflow.com/a/48297002/8490014

The problem has been solved but because of for each loop the output is getting repeated as many times as there are values in the array. How can we get the output repeating the output?


Solution

  • The problem has been solved by adding a foreach loop:

    <?
    $s = "2,3,11,12,13";
    $ss = "1,2,3,5";
    
    $catid = explode(",", $s);
    $ocat = explode(",",$ss);
    
        foreach($ocat as $abc) {
    if(in_array($abc, $catid)) {
     echo "success";
    }
    else {
    echo "fail";
    }
    }
    ?>