Search for 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, E-Commerce, Articles, Railway List1.

Is there any php function to display?

I got the result for an exact match. But there is no result for this type of search.

Please help me find a solution.

+5
source share
3 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>";
      }
}
+2
source

, stristr. , . . , FALSE.

:

<?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

+1

This solution applies only to this text template: word1, word2, word3

<?php
$text = 'Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1.';


function search_in_text($word, $text){

 $parts = explode(", ", $text);
 $result = array();
 $word = strtolower($word);

 foreach($parts as $v){

  if(strpos(strtolower($v), $word) !== false){
   $result[] = $v;
  }

 }

 if(!empty($result)){
    return implode(", ", $result);
 }else{
    return "not found";
 }
}

echo search_in_text("bank", $text);
echo search_in_text("none", $text);
?>

output:

Bank-List1, Bank-List2
not found
+1
source

All Articles