Accessing Substrings in PHP
Posted by admin | Posted in PHP, Software Programs, Theory Subjects | Posted on 19-11-2009
0
If we want to know if a string contains a particular substring. For example, you want to find out if an email address contains a @
Use strpos( )
Finding a substring with strpos( )
<?php
if (strpos($_POST['email'], '@') === false) {
print 'There was no @ in the e-mail address!';
}
?>
The return value from strpos( ) 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 notidentity operator (!==) instead of regular equals (==) or not-equals (!=).
