Given a random string

$str1= "hello my name is jeff i am somewhat new to programming and i am here trying to figure out the basics!! It has once been said that \"PHP is the best and easiest to use\" i am still trying to find this for myself";

how do i determine if this string contains the string:

$str2 = "said that";

?

    Use strstr or strpos.

    According to the manual, you should always use strpos if you're just trying to find a needle in a haystack.

    if (strpos($needle,$haystack)===false) {
        // Needle is NOT in the Haystack
    } else {
        // Needle is in the Haystack
    }
      if (strpos($str1,"said that")) {
        echo "found";
      } else {
        echo "not found";
      }
      
        5 days later

        actually this code does not work for all cases.

         if (strstr($str1, $find)) 
        { 
          echo "found"; 
        } 
        else 
        { 
          echo "not found"; 
        } 

        is a better choice.

          I see no difference....
          Your question:

          how do i determine if this string contains the string:
          $str2 = "said that";

          Thorpe's answer:

          if (strpos($str1,"said that")) {
            echo "found";
          } else {
            echo "not found";
          } 

          You wanted it generalized? Then your question should have been formed like:
          [indent]I want to search for a string within a string, but the needle and haystack may be different at any point in time. How can I do this?[/indent]
          That would get you an answer of:

          if (strstr($str1, $find))
          {
            echo "found";
          }
          else
          {
            echo "not found";
          }

          Which is no different than just generalizing what Thorpe said....

          ~Brett

            his worked great except when the substring began at the first character of the parents string, then it returned:

            "not found"

            So thank you very much to Thorpe for the help, but it was not EXACTLY what i needed.

            It was the function used not whether or not a variable was used instead of a static. 😉

              Write a Reply...