2

How can I find an highlight a string in a foreach?

This loops through all users of my database and I want to find all lets say $um.

$um = "Um";
foreach($users as $user){
     # find here the string um or something
     echo $user;
}

How do I accomplish this?

Slark
  • 31
  • 1
  • 5
  • take a look at [strpos](http://php.net/manual/en/function.strpos.php) and [str_replace](http://php.net/manual/en/function.str-replace.php). try to figure out how to use it by yourself. if you need more help let us know ;) – Tanuel Mategi Oct 26 '15 at 08:24
  • Take a look at this [question](http://stackoverflow.com/questions/17422370/highlight-only-typed-keywords-from-string-in-php). – Thaillie Oct 26 '15 at 08:24
  • 1
    Why not use the MySQL to do the check? `WHERE user LIKE '%um%'`? – Geoff Atkins Oct 26 '15 at 08:24
  • Possible duplicate of [List of Big-O for PHP functions](http://stackoverflow.com/questions/2473989/list-of-big-o-for-php-functions) – l'L'l Oct 26 '15 at 08:26
  • Why would it better to use this in the query? – Slark Oct 26 '15 at 08:33

3 Answers3

5

In reality, I would do this in the query.. ..but

$um = "Um";

foreach($users as $user){

    if(strpos($user,$um) !== false){

        echo $user;

    }
}

strpos() returns a string position, so a return value of '0' would be a match at the beginning of the string. So, check for 'not false' http://php.net/manual/en/function.strpos.php

MaggsWeb
  • 3,018
  • 1
  • 13
  • 23
4
   $um  = "this is string contains um";

  $keyword[] = "um"; // the word/parts you wanna highlight

  $result = $um;

  foreach($keyword as $key)   {


    $result = str_replace($key, "<strong>$key</strong>", $result);
  }               


echo $result;
monirz
  • 534
  • 5
  • 14
1

You could use preg_match

$um = "Um";
foreach($users as $user){
     if( preg_match( "@$um@", $user, $matches ) ) echo $user;
}
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46