Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

See if one string contains another string

Tags:

php

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!

like image 938
sark9012 Avatar asked Mar 24 '26 10:03

sark9012


1 Answers

One way, of many, would be to use the strpos() 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), strstr() is a good way to go.

like image 99
Mark Biek Avatar answered Mar 25 '26 23:03

Mark Biek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!