How to see if one string contains another string?

See if one string contains another string

  • I use the following code to check if a string is the session username at the moment. if($_SESSION['username'] == $home || $_SESSION['username'] == $away) I am looking to change that to see if the string includes the session username, not specifically IS the username. Is there a way to do this? Thankyou Edit : Say the string is "Username1 and Username2", I will "Username1" to be found. I have done the following: if( ( strpos($home, $_SESSION['username']) !== false) || ( strpos($away, $_SESSION['username']) !== false) ) That doesnt appear to have worked though!

  • Answer:

    One way, of many, would be to use the http://us.php.net/manual/en/function.strpos.php function, which the documentation says is the fastest way to just determine if a substring occurs within a string. if( strpos($_SESSION['username'],$home) ) !== false) The format of strpos is strpos(*haystack*, *needle*). So, the above would be true if $_SESSION['username'] is Username1 and $home is Username1 and Username2. If you actually need the substring back (rather than a position), http://us.php.net/manual/en/function.strstr.php is a good way to go.

Luke at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

This would work $username = 'theusername'; if(strpos($username,$_SESSION['username']) !== false)) { // contains username }

Neil Aitken

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.