note 108209 added to function.preg-match

From: Date: Sat, 07 Apr 2012 22:32:15 +0000
Subject: note 108209 added to function.preg-match
Groups: php.notes 
Request: Send a blank email to php-notes+get-187010@lists.php.net to get a copy of this message
Matching a backslash character can be confusing, because double escaping is needed in the pattern: first for PHP, second for the regex engine <?php //match newline control character: preg_match('/\n/','\n'); //pattern matches and is stored as control character 0x0A in the pattern string preg_match('/\\\n/','\n'); //very same match, but is stored escaped as 0x5C,0x6E in the pattern string //trying to match "\'" (2 characters) in a text file, '\\\'' as PHP string: $subject = file_get_contents('myfile.txt'); preg_match('/\\\'/',$subject); //DOESN'T MATCH!!! stored as 0x5C,0x27 (escaped apostrophe), this only matches apostrophe preg_match('/\\\\\'/',$subject); //matches, stored as 0x5C,0x5C,0x27 (escaped backslash and unescaped apostrophe) preg_match('/\\\\\\\/',$subject); //also matches, stored as 0x5C,0x5C,0x5C,0x27 (escaped backslash and escaped apostrophe) //matching "\n" (2 characters): preg_match('/\\\\n/','\\n'); preg_match('/\\\n/','\\n'); //same match - 3 backslashes are interpreted as 2 in PHP, if the following character is not escapeable ?> ---- Server IP: 87.106.1.137 Probable Submitter: 77.64.130.58 ---- Manual Page -- http://www.php.net/manual/en/function.preg-match.php Edit -- https://master.php.net/note/edit/108209 Del: integrated -- https://master.php.net/note/delete/108209/integrated Del: useless -- https://master.php.net/note/delete/108209/useless Del: bad code -- https://master.php.net/note/delete/108209/bad+code Del: spam -- https://master.php.net/note/delete/108209/spam Del: non-english -- https://master.php.net/note/delete/108209/non-english Del: in docs -- https://master.php.net/note/delete/108209/in+docs Del: other reasons-- https://master.php.net/note/delete/108209 Reject -- https://master.php.net/note/reject/108209 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#187010) next »