You want to know if a string contains a particular substring. For example, you want to find out if an email address contains an @.
Use strpos(string haystack, string needle, int [offset]). The return value is the first position in the string (the "haystack") at which the substring (the "needle") was found. If the needle wasn't found at all in the haystack, strpos() returns false. If the needle is at the beginning of the haystack, strpos() returns 0, since position 0 represents the beginning of the string. To differentiate between return values of 0 and false, you must use the identity operator (===) or the not-identity operator (!==) instead of regular equals (==) or not-equals (!=).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN"> <head> <title>PHP</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php $hello = 'Hello World'; echo $hello, "<br />"; echo "Find o at position: ", strpos($hello, 'o'), "</br />"; echo "Start searching at position 5:</br />"; echo "Find o at position: ", strpos($hello, 'o', 5), "</br />"; echo "<p>Looking for a.</p>"; $result = strpos($hello, 'a'); if ($result === false) echo "Not found"; else echo "Found at position $result."; ?> </p> </body> </html> |