Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search a word in a string using php function

When i search for "bank", it should display Bank-List1, Bank-List2 from the following list.

Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1.

Is there is any php function to display?

I got the output for exact match. But no result for this type of search.

Please help me to find the solution.

like image 706
raghu Avatar asked Oct 04 '22 13:10

raghu


2 Answers

you can use stristr

stristr — Case-insensitive strstr()

<?php    // Example from PHP.net
  $string = 'Hello World!';
  if(stristr($string, 'earth') === FALSE) {
    echo '"earth" not found in string';
  }
// outputs: "earth" not found in string
?> 

So for your situation, if your list was in an array named $values

you could do

foreach($values as $value)
{
      if(stristr($value, 'bank') !== FALSE) 
      {
        echo $value."<br>";
      }
}
like image 95
Hanky Panky Avatar answered Oct 10 '22 03:10

Hanky Panky


You can do it using stristr. This function returns all of haystack starting from and including the first occurrence of needle to the end. Returns the matched sub-string. If needle is not found, returns FALSE.

Here is the complete code:

<?php

  $str="Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1";
  $findme="bank";
  $tokens= explode(",", $str);
  for($i=0;$i<count($tokens);$i++)
  {
    $trimmed =trim($tokens[$i]);
    $pos = stristr($trimmed, $findme);
    if ($pos === false) {}
    else
    {
        echo $trimmed.",";
    }
  }
?>

DEMO

like image 27
Ritesh Kumar Gupta Avatar answered Oct 10 '22 04:10

Ritesh Kumar Gupta