determine if one or more strings are contained within a single variable

Discussion in 'PHP' started by pdug175, Jan 8, 2009.

  1. #1
    Hi using the example below, how would I modify the code if the $needle was a list instead of a single string?

    Ie I want to establish if any one of the items from a list are contained within the $haystack as opposed to just one single string. Say there where 3 $needles,
    $needle = ‘other’
    $needle = ‘the’
    $needle = ‘moth’

    thank you for any help
     
    pdug175, Jan 8, 2009 IP
  2. tfraymond

    tfraymond Active Member

    Messages:
    27
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    68
    #2
    If $needle is an array, simply walk through the array using strpos(), i.e.
    <?php
    $needles=array("Moe","Larry","Curly","Shemp","Joe","Curly Joe");
    foreach ($needles as $needle) {
    $pos=strpos($haystack,$needle);
    if($pos) print "Yahoo!\n";
    }
     
    tfraymond, Jan 8, 2009 IP
  3. forkaya

    forkaya Peon

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Loop through the needles
     
    forkaya, Jan 8, 2009 IP
  4. yoavmatchulsky

    yoavmatchulsky Member

    Messages:
    57
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    48
    #4
    If you don't mind a little overhead in your script, I like this approach:
    
    $needles = array ('one', 'two', 'three');
    $needles_regex = '![' . explode('|', $needles) . ']!';
    if (preg_match($needles_regex, $haystack, $matches))
    {
    // one or more needles were found
    }
    
    PHP:
     
    yoavmatchulsky, Jan 8, 2009 IP
  5. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #5

    Until you're $needles contain something like |, [, ], (, ) or / and break your RegEx...

    (I assume you meant to use implode rather than explode...)
     
    Danltn, Jan 8, 2009 IP
  6. yoavmatchulsky

    yoavmatchulsky Member

    Messages:
    57
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    48
    #6
    yea.. :)

    also, if your string is multiline, you'll need some Perl modifier for the pattern, which i don't remember exactly.

    anyway, its an idea, not a solution..
     
    yoavmatchulsky, Jan 8, 2009 IP
  7. pdug175

    pdug175 Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #7
    thanks all for your help, still a novice at PHP ... after all these years. Modified the code to do exactly what I wanted with your advice.

    Can track my warehouse traffic now : )
     
    pdug175, Jan 9, 2009 IP