SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    Trash Boat mkoenig's Avatar
    Join Date
    Aug 2007
    Posts
    1,232
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Checking string for items listed in array

    I've been looking online for this solution figured i'd post the question up.

    I know i did this years ago but can't find the code and cant get a preg_match to work.

    I want to check the variable $title that has been assigned for items in array and if there are any matches return a message or perform an action.

    PHP Code:
    //example title
    $title "Me Brown wears a yellow hat sometimes";

    //example array
    $good = array("yellow","green","pink","blue","purple","black"); 
    Any help is appreciated.

    Thanks Sitepoint!

  2. #2
    SitePoint Enthusiast
    Join Date
    Sep 2011
    Posts
    69
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you don't need all matches, you can try the following

    PHP Code:
    $title "Me Brown wears a yellow hat sometimes";
    $good = array("yellow""brown""green""pink""blue""purple""black");
    $pattern '#(' implode("|"$good) . ')#i';
    if (
    preg_match($pattern$title))
    {
            echo 
    "matches";


  3. #3
    Trash Boat mkoenig's Avatar
    Join Date
    Aug 2007
    Posts
    1,232
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you very much gvre you are the best that worked just fine.

    Yeah i just needed 1 to match not all.

    Thanks for the help!

  4. #4
    SitePoint Enthusiast Adam Chrapkowski's Avatar
    Join Date
    Sep 2011
    Location
    Poland
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If I understand well you want to check that an element from array exists in the string?
    PHP Code:
    <?php
      header
    ("content-type:text/plain;charset=utf-8");
      
    $_title "Me Brown wears a yellow hat sometimes";
      
    $_array = array("yellow","green","pink","blue","purple","black");
      
      foreach(
    $_array as $_item) {
        if( 
    preg_match("/$_item/"$_title) ) {
          echo 
    "{$_item} item found\n";
        }
      }
    ?>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •