PHP Find Variable in String

Since I always try to remember what this code is, and I can never remember, I thought I’d add it to my blog so I never forget. 🙂

This searches a string of text and finds a user defined variable. Very handy.

$string = "PHP";
$container = "I love writing PHP code.";

if(strstr($container,$string)) {
echo "found it.";
} else {
echo "not found.";
}

26 Comments

  1. Here’s another way to get the same result:

    $string = “PHP”;
    $container = “I love writing PHP code.”;

    echo (strstr($container,$string)?”found it.”:”not found.”);

  2. Hi,

    I have used the original method since it allows me to execute certain code based upon found or not found criteria. This article was very helpfull to me.

    Thanks

  3. yeah, I don’t know why PHP net always has the complicated jibba jabba when dummies like myself use that site as well. I searched high and low for about ten minutes just now until you solved my problem in laymens terms. Thanks!

  4. $haystack=”Hi jane, you look great.”;
    $needle=”jaNe”;

    if (stristr($haystack,$needle)){
    print “Yup! i found it.”;
    }
    else{
    print “Nope, i don’t see it.”;
    }

  5. You, are, Legend.

    Exactly the last piece to my puzzle!

    Was struggling to write a “if .co.uk is in string then..” statement.

  6. it’s cool but it can result only one.
    what can i do to get all find results.
    for example in
    “hello. i am a php developer. i am darklord”
    when i serach
    “i am”
    there are 2 in this paragraph.

  7. Just wanted to say thanks for posting this. I always forget the easiest way to do this and have come across your site every time I look for the solution. You’ve helped me many times.

    -AJay

  8. ok, is there a way to search in string for several item previously collected in a array

    for example

    stristr($haystack,$array_needle)

  9. How to implement with regular expreccion?, example error:

    $page = //This is te html content with url to $string
    $string = “/^http:\/\/bloat.me\/(.{4})/”;

    if(strstr($page,$string)) {
    echo “found it.”;
    } else {
    echo “not found.”;
    }

    tanks

  10. You should note that your code returns 0 (ie. the equivalent to false) if the needle is found in the very beginning of the haystack (position 0). To prevent this, use strict comparison:

    if(strstr($container,$string) === false) {
    echo “found it.”;
    } else {
    echo “not found.”;
    }

Leave a Reply