1

I'm trying to make a simple search box that uses strposto check if the entered keyword makes a match with a variable. I have this working perfectly, however I can't seem to get it to work with multiple variables. Also I can't work out how to get it to output which variable has made the match.

I thought something along the lines of this would work for checking multiple variables but I was sadly mistaken:

$pos = strpos($mystring1, $mystring2, $findme);

If anyone can help here that would be great, this is the code I currently have working for one variable.

PHP

<?
if(isset($_POST["searchString"])) {
    $mystring1 = 'how are you today';
    $mystring2 = 'hello what is your name';

    $findme = $_POST["searchString"];
    $pos = strpos($mystring1, $findme);

    if ($pos !== false) {
         //found
    } else {
         //not found
    }
}
?>

HTML

<html>
    <body>
        <form action="test.php" method="post">
            <input type="text" name="searchString">
        </form>
    </body>
</html>
3

1 Answer 1

0

You could do it like this.

<?
if(isset($_POST["searchString"])) {
    $mystring1 = 'how are you today';
    $mystring2 = 'hello what is your name';

    $findme = $_POST["searchString"];
    $pos = strpos($mystring1, $findme);
    $pos2 = strpos($mystring2, $findme);

    if ($pos !== false && $pos2 !== false) {
         //found in both strings
    } else if ($pos !== false || $pos2 !== false) {
         //found in 1 of the 2 strings
    } else {
         //not found
    }


    if ($pos !== false) {
         //found in string 1
    } 
    if ($pos2 !== false) {
         //found in string 2 
    } 
}
?>
3
  • This has worked very well, thanks you. Is there a way to make this work so it's not case sensitive?
    – Mike Toms
    Sep 4, 2017 at 15:59
  • strtolower() on both variables that you are compating. mb_strtolower() on both variables that you are comparing if you use unicode. Sep 5, 2017 at 6:48
  • Or just use stripos(), of course. Apr 28, 2023 at 6:57

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.