note 102877 added to language.types.type-juggling

From: Date: Fri, 11 Mar 2011 19:01:34 +0000
Subject: note 102877 added to language.types.type-juggling
Groups: php.notes 
Request: Send a blank email to php-notes+get-177804@lists.php.net to get a copy of this message
Checking for strings to be integers? How about if a string is a float? <?php /* checks if a string is an integer with possible whitespace before and/or after, and also isolates the integer */ $isInt=preg_match('/^\s*([0-9]+)\s*$/', $myString, $myInt); echo 'Is Integer? ', ($isInt) ? 'Yes: '.$myInt[1] : 'No', "\n"; /* checks if a string is an integer with no whitespace before or after */ $isInt=preg_match('/^[0-9]+$/', $myString); echo 'Is Integer? ', ($isInt) ? 'Yes' : 'No', "\n"; /* When checking for floats, we assume the possibility of no decimals needed. If you MUST require decimals (forcing the user to type 7.0 for example) replace the sequence: [0-9]+(\.[0-9]+)? with [0-9]+\.[0-9]+ */ /* checks if a string is a float with possible whitespace before and/or after, and also isolates the number */ $isFloat=preg_match('/^\s*([0-9]+(\.[0-9]+)?)\s*$/', $myString, $myNum); echo 'Is Number? ', ($isFloat) ? 'Yes: '.$myNum[1] : 'No', "\n"; /* checks if a string is a float with no whitespace before or after */ $isInt=preg_match('/^[0-9]+(\.[0-9]+)?$/', $myString); echo 'Is Number? ', ($isFloat) ? 'Yes' : 'No', "\n"; ?> ---- Server IP: 64.71.164.2 Probable Submitter: 68.217.6.142 ---- Manual Page -- http://www.php.net/manual/en/language.types.type-juggling.php Edit -- https://master.php.net/note/edit/102877 Del: integrated -- https://master.php.net/note/delete/102877/integrated Del: useless -- https://master.php.net/note/delete/102877/useless Del: bad code -- https://master.php.net/note/delete/102877/bad+code Del: spam -- https://master.php.net/note/delete/102877/spam Del: non-english -- https://master.php.net/note/delete/102877/non-english Del: in docs -- https://master.php.net/note/delete/102877/in+docs Del: other reasons-- https://master.php.net/note/delete/102877 Reject -- https://master.php.net/note/reject/102877 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#177804) next »