note 76356 added to function.ereg

From: Date: Wed, 11 Jul 2007 20:26:13 +0000
Subject: note 76356 added to function.ereg
Groups: php.notes 
Request: Send a blank email to php-notes+get-128391@lists.php.net to get a copy of this message
Save yourself some headache and time, don't use the \d (digits) \w (alphanumeric) and \s (whitespace) short forms. Not only do they make the code less readable, they don't seem to work with ereg. Use [0-9], [A-Za-z0-9], [ \n\r\t] instead. Since the regex example in this article is a bit on the complex side, I'll throw in a simpler regex example: Say you want to validate valid variable names: <?php $regex_valid_variable_name = '^[A-Za-z_][A-Za-z0-9_]*$'; // ^ in this context means that the regex is anchored // to the beginning of the string. // // A single [xxx] means that a single letter must mach // the criteria within // // The [xxx]* means that [xxx] can mach from zero to // unlimited times. // // The $ is another anchor, except it is for the end of // the sting. // Valid names: "_", "hello1", "a_variable" // Invalid names: "4number", "five-to", "one two", " space " //Test it out: $regx = $regx_valid_variable_name; $valid = array ( '_', 'hello1', 'a_variable' ); $invalid = array ( '4number', 'five-to', 'one two', ' space '); foreach($valid as $v) echo 'Valid '.(ereg($regx, $v) ? 'yes' : '<b>no</b>') . ": $v<br />\n"; foreach($invalid as $v) echo 'Invalid '.(!ereg($regx, $v) ? 'yes' : '<b>no</b>') . ": $v<br />\n"; ?> ---- Server IP: 62.73.196.231 Probable Submitter: 84.202.50.117 ---- Manual Page -- http://www.php.net/manual/en/function.ereg.php Edit -- https://master.php.net/note/edit/76356 Del: integrated -- https://master.php.net/note/delete/76356/integrated Del: useless -- https://master.php.net/note/delete/76356/useless Del: bad code -- https://master.php.net/note/delete/76356/bad+code Del: spam -- https://master.php.net/note/delete/76356/spam Del: non-english -- https://master.php.net/note/delete/76356/non-english Del: in docs -- https://master.php.net/note/delete/76356/in+docs Del: other reasons-- https://master.php.net/note/delete/76356 Reject -- https://master.php.net/note/reject/76356 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#128391) next »