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?

5
  • take a look at strpos and str_replace. try to figure out how to use it by yourself. if you need more help let us know ;) Commented Oct 26, 2015 at 8:24
  • Take a look at this question. Commented Oct 26, 2015 at 8:24
  • 1
    Why not use the MySQL to do the check? WHERE user LIKE '%um%'? Commented Oct 26, 2015 at 8:24
  • Possible duplicate of List of Big-O for PHP functions Commented Oct 26, 2015 at 8:26
  • Why would it better to use this in the query? Commented Oct 26, 2015 at 8:33

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

I recommend and to check the mb_strpos if the work involves different languages with special chars..
Why would it better to use this in the query?
Because it would necessitate the need for a loop, a test, and would only return the results that you want to display.
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;

2 Comments

Good one. This is the direct answer.
This worked the only thing is that it does not style single characters just the full word
1

You could use preg_match

$um = "Um";
foreach($users as $user){
     if( preg_match( "@$um@", $user, $matches ) ) echo $user;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.