Search code examples
phpregexstrpos

Finding particular words in string


I want to search the string which contains Rathi 25mm but I don't want to use the complete word to search .How can i do the search using specific words?

Rathi Stelmax 500 25 mm in stripos

   <?php
    $title='Rathi Stelmax 500 25 mm';

    if (stripos(strtolower($title), 'Rathi  25 mm') !== false)
    { 
      echo 'true';
    }
    ?>

Solution

  • There are a few ways to do this. Using your current approach you can run multiple striposs in the conditional to confirm each word is there:

    $title='Rathi Stelmax 500 25 mm';
    if (stripos(strtolower($title), 'Rathi') !== false && stripos(strtolower($title),  '25 mm'))
        { echo 'true';
        }
    

    Demo: https://eval.in/628147

    You also could use a regex such as:

    /Rathi.*25 mm/
    

    PHP Demo: https://eval.in/628148
    Regex Demo: https://regex101.com/r/cZ6bL1/1

    PHP Usage:

    $title='Rathi Stelmax 500 25 mm';
    if (preg_match('/Rathi.*25 mm/', $title)) { 
         echo 'true';
    }