Few very common String Functions in PHP

Here are few very common string functions in PHP for those who are new to PHP.  In that case just familiarize with these functions.

addslashes

Add backslash () before characters that need to be quoted before inserting into database. Those characters where backslash will be added are single quote ('), double quote ("), backslash itself () and NULL.

It is automatically added in PHP due to magic_quote_gpc directive in php.ini. And it is recommended to use database specific quoting function. Like for MySQL function is mysql_real_escape_string().

explode

array explode ( string $delimiter , string $string [, int $limit ] )

Return array after splitting a string.

$str = 'One|Two|Three';

print_r( explode('|', $str) );

htmlentities / html_ entity_ decode

Htmlentities will convert the character which have equivalent html entity into html entity. To get back the original character, html_entity_decode is used.


<?php
$str = '<b> Hello! How are you </b>';
$str1 =  htmlentities ($str, ENT_QUOTE);
echo $str1;
echo '<br>';
echo html_entities_decode($str1);
?>

ENT_QUOTE converts both double and single quotes. check for ENT_COMPAT and ENT_NOQUOTES.

htmlspecialchars / htmlspecialchars_decode

htmlspecialchars is similar to htmlentities. Function htmlentities() translate all possible characters to html entities whereas htmlspecialchars() only translate these characters - ampersand, single quote, double quote, less than and greater than sign. Again, htmlspecialchars_decode() will get back the encoded string from use of htmlspecialchars().

implode

Create string with array elements attached by provided glue.


<?php
$arr = array('Satya', 'Prakash');
echo implode(' ', $arr);
?>

nl2br

Return HTML line break before the string newline.

string nl2br ( string $string [, bool $is_xhtml = true ] )
<?php
$str = 'Hello Matt! nHow are you?';

echo nl2br ($str);
?>
Output: Hello Matt! <br>

How are you?

strip_ tags

Strip HTML and PHP tags from the data. You can select the allowed HTML tag on your data.


<?php
$str = 'I like <i><b>PHP, HTML and CSS</b></i>.';
echo strip_tags($str);  // remove all HTML tags
echo '<br>';
echo strip_tags($str, '<i>'); // allow <i> tag
?>

stripos / strpos()

stripos() will look for the first occurrence of needle. This function will return the position of the first occurrence of string.

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

optional offset can tell from where to start searching in haystack.


<?php
$str = 'An error occurred in the processing time. Sorry for inconvenience.<br> Error Code: 122333';
if (stripos($str, 'ERROR CODE') !== false)
{
echo '<p>Error returned in processing.</p>';
}
?>

In the comparison, type comparison is important as the returned value can be 0 (zero), which can evaluate to false. If the search string found at start of the haystack then zero will be returned. SO, always compare using === or !== .

stripos() and strpos() is same expect stripos() is case insensitive.

stripslashes

Un-quote the quoted string. It removes the slash added in quoting the string.

<input type="text" value="<?php echo isset($_POST['name'])?stripslashes($_POST['name']):$name;?>" name="name" >

values are quoted as magic_quotes_gpc is on by default on PHP setting. So, if magic_quotes_gpc is on, for using database specific quote function (mysql_real_escape_string for MySQL), apply stripslashes() and then use database specific function for quoting it.

strlen

Like count() for array, it returns length of string. A single character can be multibyte, which be take more than one byte of storage. Example is Japanese character, which can take upto 6 bytes. For multibyte use mb_strlen().

strtolower/strtoupper

strtoupper() convert string to upper case and strtolower() to lower case.

trim

Very useful function for trimming characters at Start and End of string. By default, it will remove all whitespace characters (tab, linefeed, carriage return,..). It also accepts parameters for the character you want to remove. It also accepts range for trimming.


<?php
echo $str = "n Example 1 :: Abc, Example 2 :: Def 9";
echo '<br>';
echo trim($str);
echo '<br>';
echo trim($str, '0..9');
//echo trim($str, '30..39'); // hex for 0 to 9
?>

Output:

Example 1 :: Abc, Example 2 :: Def 9
Example 1 :: Abc, Example 2 :: Def 9
Example 1 :: Abc, Example 2 :: Def

chr

Return a character specified by ASCII value. So, ASCII code to character code.

<?php
print chr(7);
?>

Check for ord();

Check for ord, wordwrap and other string functions here.

http://www.php.net/manual/en/ref.strings.php