Recipe 1.1. Accessing Substrings


1.1.1. Problem

You want to know if a string contains a particular substring. For example, you want to find out if an email address contains a @.

1.1.2. Solution

Use strpos( ) , as in Example 1-8.

Finding a substring with strpos( )

<?php if (strpos($_POST['email'], '@') === false) {     print 'There was no @ in the e-mail address!';  } ?>

1.1.3. Discussion

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 (!=). Example 1-8 compares the return value from strpos( ) to false using ===. This test only succeeds if strpos returns false, not if it returns 0 or any other number.

1.1.4. See Also

Documentation on strpos( ) at http://www.php.net/strpos.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net