1.9 Escaping Special Characters in a String


1.9 Escaping Special Characters in a String

You need to escape certain characters in a string.

Technique

Use the addslashes() or quotemeta() function, depending on what you need:

 <?php $str         = "Well now, how's it going Mike?"; $slashed_str = addslashes ($str); // $str is now "Well now how\ 's it going Mike?" $str         = "The $ is mine, ain't it?"; $escaped_str = quotemeta ($str); // $str is now "The $ is mine, ain't it\?" ?> 

Comments

When manipulating data in databases using SQL queries, it is often necessary to escape the ', ", and NULL characters because they are considered special by some database systems. PHP offers the addslashes() function, which will add slashes before these characters, thus escaping them.

The quotemeta() function should be used to escape data before you pass it to a regular expression. This ensures that when you put variable data into a regular expression, doing so won't screw up the results. (Use the preg_quote() function if you need to quote a string that is being used with the Perl-compatible regular expression functions.)

PHP also has support for encoding and decoding a URL through the urldecode() and urlencode () functions.

 <?php $str = "Welcome to John's World"; $str = urlencode ($str); /* $str is now "Welcome+to+John%27s+World" */ $str = urldecode ($str); /* $str is now "Welcome to John's World" */ ?> 

Another thing you might want to do is escape HTML entities in a string. To achieve this, you can use PHP's built-in htmlspecialchars() function.

 <?php $str = 'Shakespeares "Hamlet" is a wonderful work.'; print htmlspecialchars ($str); ?> 

This will output "Shakespeares &quot;Hamlet&quot; is a wonderful work." , which can be safely displayed in a text area. Note that if you want to escape characters other than & , " , < , and > , you should use the htmlentities() function, which escapes all HTML entities (not just & , " , < , and > ).



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net