raghu
raghu

Reputation: 317

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.

Upvotes: 5

Views: 9507

Answers (3)

user1646111
user1646111

Reputation:

This solution is only valid for this pattern of text is like: 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

Upvotes: 1

Ritesh Kumar Gupta
Ritesh Kumar Gupta

Reputation: 5191

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

Upvotes: 1

Hanky Panky
Hanky Panky

Reputation: 46900

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>";
      }
}

Upvotes: 2

Related Questions