Monday, March 16, 2009

String functions in PHP

When working with the string we need to take care of single quotations and the backslashes. There are so many scenarios where we get error when this types of special characters raised.

There are PHP function to overcome this problems

1.addslashes

Syntax is

string addslashes ( string $str )
Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

Example:

<?php
$str = "welcome to find my solutions is your name O'reilly?";
echo addslashes($str);
?>


Output for this would be

welcome to find my solutions is your name O\'reilly?

If you did not use this function it shows an error.

2. stripslashes()
Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\).

Note: If magic_quotes_sybase is on, no backslashes are stripped off but two apostrophes are replaced by one instead.

An example use of stripslashes() is when the PHP directive magic_quotes_gpc is on (it's on by default), and you aren't inserting this data into a place (such as a database) that requires escaping. For example, if you're simply outputting data straight from an HTML form.

Example:

$stripped = 'In a given string there are three\\\ slashes';
$stripped = stripslahses($stripped);

Output of the above will be
'In a given string there are three\ slashes'

$stripped = 'In a given string there are three\\\ slashes';
$stripped = stripslahses(stripslashes($stripped));


The output would be
'In a given string there are three'

0 comments:

Post a Comment