note 73070 rejected from function.preg-replace by nlopess

From: Date: Wed, 07 Feb 2007 23:53:56 +0000
Subject: note 73070 rejected from function.preg-replace by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-123101@lists.php.net to get a copy of this message
Note Submitter: phpcoder at cyberpimp dot sexventure dot com ---- A bug exists in the REGEX engine, preventing preg_replace from outputting NULL characters. (They end up as a literal '\0' instead.) As a workaround, you can use str_replace() to handle NULLs. Here are some examples of 4 functions for URL validation and HTML encoding using preg_replace(), with the str_replace() workaround, making them binary-safe and able to handle NULLs: <?php /* **BINARY-SAFE** URL-validator and various HTML-encoders by Justin Frim Feel free to use in your own code. */ function url_validate($uncertainURL){ //URL validator return preg_replace('/([\\x01-\\x20"<>`\\x7F-\\xFF])/e', "'%'.sprintf('%02X',ord('\\1'))", str_replace("\0",'%00',$uncertainURL)); } function ASCII_htmlspecialchars($literaldata){ //HTML encoder //Only outputs printable ASCII. return preg_replace('/([\\x01-\\x19\\x7F-\\xFF])/e', "'&#'.ord('\\1').';'", str_replace("\0",'&#0;',htmlspecialchars($literaldata)); } function ASCII_CRLF_htmlspecialchars($literaldata){ //HTML encoder //Only outputs printable ASCII, CRs, and LFs. return preg_replace('/([\\x01-\\x09\\x0B\\x0C\\x0E-\\x1F \\x7F-\\xFF])/e', "'&#'.ord('\\1').';'", str_replace("\0",'&#0;',htmlspecialchars($literaldata))); } function ASCII_nl2br_htmlspecialchars($literaldata){ //HTML encoder w. newline translation //Only outputs printable ASCII, CRs, and LFs. return nl2br(preg_replace( '/([\\x01-\\x09\\x0B\\x0C\\x0E-\\x1F \\x7F-\\xFF])/e', "'&#'.ord('\\1').';'", str_replace("\0",'&#0;',htmlspecialchars($literaldata)))); } ?> Typical uses: url_validate(): Ensure a string (assumed to be a URL) is URL-compliant. Only encodes any unsafe characters found in the string. (Reserved characters are left as-is.) ASCII_htmlspecialchars(): Replacement for htmlspecialchars(), ensuring all control characters and high 8-bit characters are represented with printable ASCII HTML codes. Ideal for outputting text or binary data as HTML tag parameters. ASCII_CRLF_htmlspecialchars(): Same as above, but allowing CRs and LFs to pass through unencoded. Use for outputting non-display text to an HTML document where newlines must be retained in the HTML source, or display text if newlines are to appear simply as spaces. ASCII_nl2br_htmlspecialchars(): Same as above, but adding <br \> before any CRs, LFs, CRLFs, and LFCRs. Use for outputting display text to an HTML document, keeping the appearance of newlines intact. (Note that it can NOT be used for tag parameters!)

« previous php.notes (#123101) next »