|
STRINGS This article is about manipulating Strings. FINDING A SUBSTRING Imagine that you want to check that a photo file has a " .jpg " extension. The following examples will do that: JAVASCRIPT This script uses the " indexOf() " method and returns " -1 " if no match is found. <script type = "text/javascript"> var str = "daftwat.jpg"; var jpg = str.indexOf(".jpg"); var result = "Not a jpg file"; if( jpg != -1 ){ result = "jpg file"; } alert( result ); </script> PHP This script does the same job, using PHP. Who says that you can't find a needle in a haystack? The ' stristr() ' function performs a case insensitive search, otherwise use ' strstr() ' if you want to match the case. <?php //=================================== Create string to search $haystack = "daftwat.JPG"; //=================================== case insensitive search $needle = stristr( $haystack, ".jpg" ); //=================================== give initial value to result $result = "File is a jpg format"; if( ! $needle ){ //=================================== change value of result $result = "Not a jpg file"; } //==================================== print result echo( $result ); ?> NOTES If some daftwat creates a silly file, for example, " daftwat.jpgxx " the scripts will report, " jpg file ". So you will have to decide whether to program for that unlikely possibility. |