You are on page 1of 111

Created By www.ebooktutorials.blogspot.

in

PHP String Introduction


The string functions allow you to manipulate strings.

Installation
The string functions are part of the PHP core. There is no installation needed to use these functions.

PHP String Functions


PHP: indicates the earliest version of PHP that supports the function. Function addcslashes() addslashes() bin2hex() chop() chr() chunk_split() convert_cyr_string() convert_uudecode() convert_uuencode() count_chars() crc32() crypt() echo() explode() fprintf() get_html_translation_table() hebrev() hebrevc() html_entity_decode() htmlentities() htmlspecialchars_decode() htmlspecialchars() implode() join() levenshtein() localeconv() ltrim() md5() md5_file() metaphone() money_format() nl_langinfo() nl2br() number_format() ord() parse_str() print() printf() quoted_printable_decode() quotemeta() rtrim() setlocale() sha1() sha1_file() similar_text() soundex() sprintf() sscanf() str_ireplace() str_pad() str_repeat() str_replace() str_rot13() str_shuffle() str_split() str_word_count() strcasecmp() strchr() Description Returns a string with backslashes in front of the specified characters Returns a string with backslashes in front of predefined characters Converts a string of ASCII characters to hexadecimal values Alias of rtrim() Returns a character from a specified ASCII value Splits a string into a series of smaller parts Converts a string from one Cyrillic character-set to another Decodes a uuencoded string Encodes a string using the uuencode algorithm Returns how many times an ASCII character occurs within a string and returns the information Calculates a 32-bit CRC for a string One-way string encryption (hashing) Outputs strings Breaks a string into an array Writes a formatted string to a specified output stream Returns the translation table used by htmlspecialchars() and htmlentities() Converts Hebrew text to visual text Converts Hebrew text to visual text and new lines (\n) into <br /> Converts HTML entities to characters Converts characters to HTML entities Converts some predefined HTML entities to characters Converts some predefined characters to HTML entities Returns a string from the elements of an array Alias of implode() Returns the Levenshtein distance between two strings Returns locale numeric and monetary formatting information Strips whitespace from the left side of a string Calculates the MD5 hash of a string Calculates the MD5 hash of a file Calculates the metaphone key of a string Returns a string formatted as a currency string Returns specific local information Inserts HTML line breaks in front of each newline in a string Formats a number with grouped thousands Returns the ASCII value of the first character of a string Parses a query string into variables Outputs a string Outputs a formatted string Decodes a quoted-printable string Quotes meta characters Strips whitespace from the right side of a string Sets locale information Calculates the SHA-1 hash of a string Calculates the SHA-1 hash of a file Calculates the similarity between two strings Calculates the soundex key of a string Writes a formatted string to a variable Parses input from a string according to a format Replaces some characters in a string (case-insensitive) Pads a string to a new length Repeats a string a specified number of times Replaces some characters in a string (case-sensitive) Performs the ROT13 encoding on a string Randomly shuffles all characters in a string Splits a string into an array Count the number of words in a string Compares two strings (case-insensitive) Finds the first occurrence of a string inside another string (alias of strstr()) PHP 4 3 3 3 3 3 3 5 5 4 4 3 3 3 5 4 3 3 4 3 5 3 3 3 3 4 3 3 4 4 4 4 3 3 3 3 3 3 3 3 3 3 4 4 3 3 3 4 5 4 4 3 4 4 5 4 3 3

Content Downloaded From www.w3schools.com

Created By www.ebooktutorials.blogspot.in
strcmp() strcoll() strcspn() strip_tags() stripcslashes() stripslashes() stripos() stristr() strlen() strnatcasecmp() strnatcmp() strncasecmp() strncmp() strpbrk() strpos() strrchr() strrev() strripos() strrpos() strspn() strstr() strtok() strtolower() strtoupper() strtr() substr() substr_compare() substr_count() substr_replace() trim() ucfirst() ucwords() vfprintf() vprintf() vsprintf() wordwrap() Compares two strings (case-sensitive) Locale based string comparison Returns the number of characters found in a string before any part of some specified characters are found Strips HTML and PHP tags from a string Unquotes a string quoted with addcslashes() Unquotes a string quoted with addslashes() Returns the position of the first occurrence of a string inside another string (case-insensitive) Finds the first occurrence of a string inside another string (case-insensitive) Returns the length of a string Compares two strings using a "natural order" algorithm (case-insensitive) Compares two strings using a "natural order" algorithm (case-sensitive) String comparison of the first n characters (case-insensitive) String comparison of the first n characters (case-sensitive) Searches a string for any of a set of characters Returns the position of the first occurrence of a string inside another string (case-sensitive) Finds the last occurrence of a string inside another string Reverses a string Finds the position of the last occurrence of a string inside another string (caseinsensitive) Finds the position of the last occurrence of a string inside another string (casesensitive) Returns the number of characters found in a string that contains only characters from a specified charlist Finds the first occurrence of a string inside another string (case-sensitive) Splits a string into smaller strings Converts a string to lowercase letters Converts a string to uppercase letters Translates certain characters in a string Returns a part of a string Compares two strings from a specified start position (binary safe and optionally case-sensitive) Counts the number of times a substring occurs in a string Replaces a part of a string with another string Strips whitespace from both sides of a string Converts the first character of a string to uppercase Converts the first character of each word in a string to uppercase Writes a formatted string to a specified output stream Outputs a formatted string Writes a formatted string to a variable Wraps a string to a given number of characters 3 4 3 3 4 3 5 3 3 4 4 4 4 5 3 3 3 5 3 3 3 3 3 3 3 3 5 4 4 3 3 3 5 4 4 4

PHP String Constants


PHP: indicates the earliest version of PHP that supports the constant. Constant CRYPT_SALT_LENGTH CRYPT_STD_DES CRYPT_EXT_DES CRYPT_MD5 CRYPT_BLOWFISH HTML_SPECIALCHARS HTML_ENTITIES ENT_COMPAT ENT_QUOTES ENT_NOQUOTES CHAR_MAX LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_ALL LC_MESSAGES STR_PAD_LEFT STR_PAD_RIGHT STR_PAD_BOTH Description PHP Contains the length of the default encryption method for the system. For standard DES encryption, the length is 2 Set to 1 if the standard DES-based encryption with a 2 character salt is supported, 0 otherwise Set to 1 if the extended DES-based encryption with a 9 character salt is supported, 0 otherwise Set to 1 if the MD5 encryption with a 12 character salt starting with $1$ is supported, 0 otherwise Set to 1 if the Blowfish encryption with a 16 character salt starting with $2$ or $2a$ is supported, 0 otherwise0

Content Downloaded From www.w3schools.com

Created By www.ebooktutorials.blogspot.in

PHP addcslashes() Function


Definition and Usage
The addcslashes() function returns a string with backslashes in front of the specified characters.

Syntax
addcslashes(string,characters) Parameter string characters Description Required. Specifies the string to check Required. Specifies the characters or range of characters to be affected by addcslashes()

Tips and Notes


Note: Be careful using addcslashes() on 0, r, n and t. In PHP, \0, \r, \n and \t are predefined escape sequences.

Example 1
In this example we will add backslashes to certain characters in a string: <?php $str = "Hello, my name is Kai Jim."; echo $str."<br />"; echo addcslashes($str,'m')."<br />"; echo addcslashes($str,'K')."<br />"; ?> The output of the code above will be: Hello, my name is Kai Jim. Hello, \my na\me is Kai Ji\m. Hello, my name is \Kai Jim.

Example 2
In this example we will add backslashes to a range of characters in a string: <?php $str = "Hello, my name is Kai Jim."; echo $str."<br />"; echo addcslashes($str,'A..Z')."<br />"; echo addcslashes($str,'a..z')."<br />"; echo addcslashes($str,'a..h'); ?> The output of the code above will be: Hello, my name is Kai Jim. \Hello, my name is \Kai \Jim. H\e\l\l\o, \m\y \n\a\m\e \i\s K\a\i J\i\m. H\ello, my n\am\e is K\ai Jim.

Content Downloaded From www.w3schools.com

Created By www.ebooktutorials.blogspot.in

PHP addslashes() Function


Definition and Usage
The addslashes() function returns a string with backslashes in front of predefined characters. The predefined characters are: single quote (') double quote (") backslash (\) NULL

Syntax
addslashes(string) Parameter Description string Required. Specifies the string to check

Tips and Notes


Tip: This function can be used to prepare a string for storage in a database and database queries. Note: PHP runs addslashes() on all GET, POST, and COOKIE data by default. Therefore you should not use addslashes() on strings that have already been escaped, this will cause double escaping. The function get_magic_quotes_gpc() can be used to check this.

Example
In this example we will add backslashes to the predefined characters in a string: <?php $str = "Who's Kai Jim?"; echo $str . " This is not safe in a database query.<br />"; echo addslashes($str) . " This is safe in a database query."; ?> The output of the code above will be: Who's Kai Jim? This is not safe in a database query. Who\'s Kai Jim? This is safe in a database query.

Content Downloaded From www.w3schools.com

Created By www.ebooktutorials.blogspot.in

PHP bin2hex() Function


Definition and Usage
The bin2hex() function converts a string of ASCII characters to hexadecimal values. The string can be converted back using the pack() function.

Syntax
bin2hex(string) Parameter Description string Required. The string to be converted

Example
In this example we will convert a string value from binary to hex and back: <?php $str = "Hello world!"; echo bin2hex($str) . "<br />"; echo pack("H*",bin2hex($str)) . "<br />"; ?> The output of the code above will be: 48656c6c6f20776f726c6421 Hello world

Content Downloaded From www.w3schools.com

Created By www.ebooktutorials.blogspot.in

PHP chop() Function


Definition and Usage
The chop() function will remove a white space or other predefined character from the right end of a string. This function is an alias of the rtrim() function.

Syntax
chop(string,charlist) Parameter string charlist Description Required. Specifies the string to check Optional. Specifies which characters to remove from the string. The following characters are allowed and is set to be removed if the charlist parameter is empty: "\0" - ASCII 0, NULL "\t" - ASCII 9, a tab "\n" - ASCII 10, a new line "\x0B" - ASCII 11, a vertical tab. "\r" - ASCII 13, a carriage return " " - ASCII 32, an ordinary white space

Example
In this example we will use the chop() function to remove characters from the right end of a string: <?php $str = "Hello World!\n\n"; echo $str; echo chop($str); ?> The source output of the code above will be: <html> <body> Hello World! Hello World!</body> </html> The browser output of the code above will be: Hello World! Hello World!

Content Downloaded From www.w3schools.com

Created By www.ebooktutorials.blogspot.in

PHP chr() Function


Definition and Usage
The chr() function returns a character from the specified ASCII value.

Syntax
chr(ascii) Parameter Description ascii Required. An ASCII value

Tips and Notes


Note: The x parameter can be specified in decimal, octal, or hex values. Octal values are defined by a leading 0, while hex values are defined by a leading 0x.

Example
<?php echo chr(52)."<br />"; echo chr(052)."<br />"; echo chr(0x52)."<br />"; ?> The output of the code above will be: 4 * R

Content Downloaded From www.w3schools.com

Created By www.ebooktutorials.blogspot.in

PHP chunk_split() Function


Definition and Usage
The chunk_split() function splits a string into a series of smaller parts.

Syntax
chunk_split(string,length,end) Parameter string length end Description Required. Specifies the string to split Optional. A number that defines the length of the chunks. Default is 76 Optional. A string that defines what to place at the end of each chunk. Default is \r\n

Tips and Notes


Note: This function does not alter the original string.

Example 1
In this example we will split the string after each character and add a "." after each split: <?php $str = "Hello world!"; echo chunk_split($str,1,"."); ?> The output of the code above will be: H.e.l.l.o. .w.o.r.l.d.!.

Example 2
In this example we will split the string after the sixth character and add "..." after each split: <?php $str = "Hello world!"; echo chunk_split($str,6,"..."); ?> The output of the code above will be: Hello ...world!...

Content Downloaded From www.w3schools.com

Created By www.ebooktutorials.blogspot.in

PHP convert_cyr_string() Function


Definition and Usage
The convert_cyr_string() function converts a string from one Cyrillic character-set to another. The supported Cyrillic character-sets are: k - koi8-r w - windows-1251 i - iso8859-5 a - x-cp866 d - x-cp866 m - x-mac-cyrillic

Syntax
convert_cyr_string(string,from,to) Parameter string from to Description Required. The string to convert Required. A character that specifies what Cyrillic character-set to convert from Required. A character that specifies what Cyrillic character-set to convert to

Example
In this example we will convert a string from one character-set to another: <?php $str = "Hello world! "; echo $str."<br />"; echo convert_cyr_string($str,'w','a'); ?> The output of the code above will be: Hello world! Hello world!

Content Downloaded From www.w3schools.com

Created By www.ebooktutorials.blogspot.in

PHP convert_uudecode() Function


Definition and Usage
The convert_uudecode() function decodes a uuencoded string.

Syntax
convert_uudecode(string) Parameter Description string Required. The uuencoded string to decode

Example
In this example we will decode a uuencoded string using convert_uudecode(): <?php $str = ",2&5L;&\@=V]R;&0A `"; echo convert_uudecode($str); ?> The output of the code above will be: Hello world!

Content Downloaded From www.w3schools.com

10

Created By www.ebooktutorials.blogspot.in

PHP convert_uuencode() Function


Definition and Usage
The convert_uuencode() function encodes a string using the uuencode algorithm.

Syntax
convert_uuencode(string) Parameter Description string Required. The string to uuencode

Tips and Notes


Note: This function encodes all strings (including binary) into printable characters. This will fix any problems with obscure binary data when storing in a database or transmit data over a network. Remember to use the convert_uudecode() function before using the data again. Note: Uuencoded data is about 35% larger than the original.

Example
In this example we will encode a string using convert_uuencode(): <?php $str = "Hello world!"; echo convert_uuencode($str); ?> The output of the code above will be: ,2&5L;&\@=V]R;&0A `

Content Downloaded From www.w3schools.com

11

Created By www.ebooktutorials.blogspot.in

PHP count_chars() Function


Definition and Usage
The count_chars() function returns how many times an ASCII character occurs within a string and returns the information.

Syntax
count_chars(string,mode) Parameter string mode Description Required. The string to be checked Optional. Specifies the return modes. 0 is default. The different return modes are: 0 - an array with the ASCII value as key and number of occurrences as value 1 - an array with the ASCII value as key and number of occurrences as value, only lists occurrences greater than zero 2 - an array with the ASCII value as key and number of occurrences as value, only lists occurrences equal to zero are listed 3 - a string with all the different characters used 4 - a string with all the unused characters

Example 1
In this example we will use count_chars() with mode 1 to check the string. Mode 1 will return an array with the ASCII value as key and how many times it occurred as value (e.g. in the example below, the ASCII value for the letter "l" is 108, and it occurs three times): <?php $str = "Hello World!"; print_r(count_chars($str,1)); ?> The output of the code above will be: Array ( [32] => 1 [33] => 1 [72] => 1 [87] => 1 [100] => 1 [101] => 1 [108] => 3 [111] => 2 [114] => 1 )

Example 2
In this example we will use the count_chars() with mode 3 to check the string. Mode 3 will return a string with all the different characters used: <?php $str = "Hello World!"; echo count_chars($str,3); ?> The output of the code above will be: !HWdelor

Content Downloaded From www.w3schools.com

12

Created By www.ebooktutorials.blogspot.in

PHP crc32() Function


Definition and Usage
The crc32() function calculates a 32-bit CRC (cyclic redundancy checksum) for a string. This function can be used to validate data integrity.

Syntax
crc32(string) Parameter Description string Required. The string to be calculated

Tips and Notes


Tip: To ensure that you get the correct string representation from the crc32() function, you'll need to use the %u formatter of the printf() or sprintf() function. If the %u formatter is not used, the result may display in incorrect and negative numbers.

Example 1
In this example we will print the result of crc32() with and without the "%u" formatter (note that the result is equal): <?php $str = crc32("Hello world!"); echo 'Without %u: '.$str."<br />"; echo 'With %u: '; printf("%u",$str); ?> The output of the code above will be: Without %u: 461707669 With %u: 461707669

Example 2
In this example we will print the result of crc32() with and without the "%u" formatter (note that the result is not equal): <?php $str = crc32("Hello world."); echo 'Without %u: '.$str."<br />"; echo 'With %u: '; printf("%u",$str); ?> The output of the code above will be: Without %u: -1959132156 With %u: 2335835140

Content Downloaded From www.w3schools.com

13

Created By www.ebooktutorials.blogspot.in

PHP crypt() Function


Definition and Usage
The crypt() function returns a string encrypted using DES, Blowfish, or MD5 algorithms. This function behaves different on different operating systems, some operating systems supports more than one type of encryption. PHP checks what algorithms are available and what algorithms to use when it is installed. The exact algorithm depends on the format and length of the salt parameter. Salts help make the encryption more secure by increasing the number of encrypted strings that can be generated for one specific string with one specific encryption method. There are some constants that are used together with the crypt() function. The value of these constants are set by PHP when it is installed. Constants: [CRYPT_SALT_LENGTH] - The length of the default encryption. With standard DES encryption, the length is 2 [CRYPT_STD_DES] - Value is 1 if the standard DES algorithm is supported, 0 otherwise. The Standard DES-based encryption has a two character salt [CRYPT_EXT_DES] - Value is1 if the extended DES algorithm is supported, 0 otherwise. The Extended DES encryption has a nine character salt [CRYPT_MD5] - Value is 1 if the MD5 algorithm is supported, 0 otherwise. The MD5 encryption has a 12 character salt starting with $1$ [CRYPT_BLOWFISH] - Value is 1 if the Blowfish algorithm is supported, 0 otherwise. The Blowfish encryption has a 16 character salt starting with $2$ or $2a$

Syntax
crypt(str,salt) Parameter str salt Description Required. Specifies the string to be encoded Optional. A string used to increase the number of characters encoded, to make the encoding more secure. If the salt argument is not provided, one will be randomly generated by PHP each time you call this function.

Tips and Notes


Note: There is no decrypt function. The crypt() function uses a one-way algorithm.

Example 1
In this example we will test the different algorithms: <?php if (CRYPT_STD_DES == 1) { echo "Standard DES: ".crypt("hello world")."\n<br />"; } else { echo "Standard DES not supported.\n<br />"; } if (CRYPT_EXT_DES == 1) { echo "Extended DES: ".crypt("hello world")."\n<br />"; } else { echo "Extended DES not supported.\n<br />"; } if (CRYPT_MD5 == 1) { echo "MD5: ".crypt("hello world")."\n<br />"; } else { echo "MD5 not supported.\n<br />"; } if (CRYPT_BLOWFISH == 1) { echo "Blowfish: ".crypt("hello world"); } else { echo "Blowfish DES not supported."; } ?> The output of the code above could be (depending on the operating system): Standard DES: $1$r35.Y52.$iyiFuvM.zFGsscpU0aZ4e.

Content Downloaded From www.w3schools.com

14

Created By www.ebooktutorials.blogspot.in
Extended DES not supported. MD5: $1$BN1.0I2.$8oBI/4mufxK6Tq89M12mk/ Blowfish DES not supported.

Content Downloaded From www.w3schools.com

15

Created By www.ebooktutorials.blogspot.in

PHP echo() Function


Definition and Usage
The echo() function outputs one or more strings.

Syntax
echo(strings) Parameter strings Description Required. One or more strings to be sent to the output

Tips and Notes


Note: The echo() function is not actually a function, so you are not required to use parentheses with it. However, if you want to pass more than one parameter to echo(), using parentheses will generate a parse error. Tip: The echo() function is slightly faster than print(). Tip: The echo() function has the following shortcut syntax. See example 5.

Example 1
<?php $str = "Who's Kai Jim?"; echo $str; echo "<br />"; echo $str."<br />I don't know!"; ?> The output of the code above will be: Who's Kai Jim? Who's Kai Jim? I don't know!

Example 2
<?php echo "This text spans multiple lines."; ?> The output of the code above will be: This text spans multiple lines.

Example 3
<?php echo 'This ','string ','was ','made ','with multiple parameters'; ?> The output of the code above will be: This string was made with multiple parameters

Example 4
Difference of single and double quotes. Single quotes will print the variable name, not the value: <?php $color = "red"; echo "Roses are $color"; echo "<br />"; echo 'Roses are $color'; ?> The output of the code above will be: Roses are red Roses are $color

Content Downloaded From www.w3schools.com

16

Created By www.ebooktutorials.blogspot.in

Example 5
Shortcut syntax: <html> <body> <?php $color = "red"; ?> <p>Roses are <?=$color?></p> </body> </html>

Content Downloaded From www.w3schools.com

17

Created By www.ebooktutorials.blogspot.in

PHP explode() Function


Definition and Usage
The explode() function breaks a string into an array.

Syntax
explode(separator,string,limit) Parameter separator string limit Description Required. Specifies where to break the string Required. The string to split Optional. Specifies the maximum number of array elements to return

Tips and Notes


Note: Separator cannot be an empty string.

Example
In this example we will break a string to an array: <?php $str = "Hello world. It's a beautiful day."; print_r (explode(" ",$str)); ?> The output of the code above will be: Array ( [0] => [1] => [2] => [3] => [4] => [5] => )

Hello world. It's a beautiful day.

Content Downloaded From www.w3schools.com

18

Created By www.ebooktutorials.blogspot.in

PHP fprintf() Function


Definition and Usage
The fprintf() function writes a formatted string to a specified output stream (example: file or database). The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc. The fprintf() function returns the length of the written string.

Syntax
fprintf(stream,format,arg1,arg2,arg++) Parameter stream format Description Required. Specifies where to write/output the string Required. Specifies the string and how to format the variables in it. Possible format values: %% - Returns a percent sign %b - Binary number %c - The character according to the ASCII value %d - Signed decimal number %e - Scientific notation (e.g. 1.2e+2) %u - Unsigned decimal number %f - Floating-point number (local settings aware) %F - Floating-point number (not local settings aware) %o - Octal number %s - String %x - Hexadecimal number (lowercase letters) %X - Hexadecimal number (uppercase letters) Additional format values. These are placed between the % and the letter (example %.2f): + (Forces both + and - in front of numbers. By default, only negative numbers are marked) ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding) - (Left-justifies the variable value) [0-9] (Specifies the minimum width held of to the variable value) .[0-9] (Specifies the number of decimal digits or maximum string length) arg1 arg2 arg++ Note: If multiple additional format values are used, they must be in the same order as above. Required. The argument to be inserted at the first %-sign in the format string Optional. The argument to be inserted at the second %-sign in the format string Optional. The argument to be inserted at the third, fourth, etc. %-sign in the format string

Tips and Notes


Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "\$". See example three. Tip: Related functions: printf(), sprintf(), vfprintf(), vprintf(), and vsprintf().

Example 1
<?php $str = "Hello"; $number = 123; $file = fopen("test.txt","w"); echo fprintf($file,"%s world. Day number %u",$str,$number); ?> The output of the code above will be: 27 The following text will be written to the file "test.txt": Hello world. Day number 123

Example 2
<?php $number = 123; $file = fopen("test.txt","w"); fprintf($file,"%f",$number); ?>

Content Downloaded From www.w3schools.com

19

Created By www.ebooktutorials.blogspot.in
The following text will be written to the file "test.txt": 123.000000

Example 3
Use of placeholders: <?php $number = 123; $file = fopen("test.txt","w"); fprintf($file,"With 2 decimals: %1\$.2f \nWith no decimals: %1\$u",$number); ?> The following text will be written to the file "test.txt": With 2 decimals: 123.00 With no decimals: 123

Content Downloaded From www.w3schools.com

20

Created By www.ebooktutorials.blogspot.in

PHP get_html_translation_table() Function


Definition and Usage
The get_html_translation_table() function returns the translation table used by the htmlentities() and htmlspecialchars() functions.

Syntax
get_html_translation_table(function,quotestyle) Parameter function Description Optional. Specifies which translation table to return. Default is HTML_SPECIALCHARS. Possible values: HTML_ENTITIES - Translates all characters that need URL-encoding to be shown properly on a HTML page HTML_SPECIALCHARS - Translates some characters that need URL-encoding to be shown properly on a HTML page quotestyle Optional. Defines how to encode single and double quotes. Default is ENT_COMPAT Possible values: ENT_COMPAT - Encodes double quotes, not single quotes ENT_QUOTES - Encodes double and single quotes ENT_NOQUOTES - Does not encode single or double quotes

Tips and Notes


Tip: Some characters can be encoded several ways. The get_html_translation_table() function returns the most common encoding.

Example
In this example we will show both translation tables.: <?php print_r (get_html_translation_table()); echo "<br />"; print_r (get_html_translation_table(HTML_ENTITIES)); ?> The output of the code above will be: Array ( ["] => " [<] => < [>] => > [&] => & ) Array ( [ ] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => [] => ["] => " [<] => < [>] => > [&] => & )

Content Downloaded From www.w3schools.com

21

Created By www.ebooktutorials.blogspot.in

PHP hebrev() Function


Definition and Usage
The hebrev() function converts Hebrew text from a right-to-left flow to a left-to-right flow. Only ASCII characters between 224 and 251, and punctuation characters will be affected.

Syntax
hebrev(string,maxcharline) Parameter string maxcharline Description Required. A Hebrew text Optional. Specifies maximum characters for each line. hebrev() will avoid breaking words if possible

Tips and Notes


Tip: hebrev() and hebrevc() can convert Hebrew logical text (the Windows encoding) to Hebrew visual text. Hebrew visual requires no special right-to-left character support to be displayed properly, making it very useful for displaying Hebrew text on the web.

Example
<?php echo hebrev(" "); ?> The output of the code above will be:

Content Downloaded From www.w3schools.com

22

Created By www.ebooktutorials.blogspot.in

PHP hebrevc() Function


Definition and Usage
The hebrevc() function converts Hebrew text from a right-to-left flow to a left-to-right flow. It also converts new lines (\n) into <br />. Only ASCII characters between 224 and 251, and punctuation characters will be affected.

Syntax
hebrevc(string,maxcharline) Parameter string maxcharline Description Required. A Hebrew text Optional. Specifies maximum characters for each line. hebrev() will avoid breaking words if possible

Tips and Notes


Tip: hebrev() and hebrevc() can convert Hebrew logical text (the Windows encoding) to Hebrew visual text. Hebrew visual requires no special right-to-left character support to be displayed properly, making it very useful for displaying Hebrew text on the web.

Example
<?php echo hebrevc(" \n "); ?> The output of the code above will be:

Content Downloaded From www.w3schools.com

23

Created By www.ebooktutorials.blogspot.in

PHP html_entity_decode() Function


Definition and Usage
The html_entity_decode() function converts HTML entities to characters. The html_entity_decode() function is the opposite of htmlentities().

Syntax
html_entity_decode(string,quotestyle,character-set) Parameter string quotestyle Description Required. Specifies the string to decode Optional. Specifies how to decode single and double quotes. The available quote styles are: ENT_COMPAT - Default. Decodes only double quotes ENT_QUOTES - Decodes double and single quotes ENT_NOQUOTES - Does not decode any quotes character-set Optional. A string that specifies which character-set to use. Allowed values are: ISO-8859-1 - Default. Western European ISO-8859-15 - Western European (adds the Euro sign + French and Finnish letters missing in ISO-88591) UTF-8 - ASCII compatible multi-byte 8-bit Unicode cp866 - DOS-specific Cyrillic charset cp1251 - Windows-specific Cyrillic charset cp1252 - Windows specific charset for Western European KOI8-R - Russian BIG5 - Traditional Chinese, mainly used in Taiwan GB2312 - Simplified Chinese, national standard character set BIG5-HKSCS - Big5 with Hong Kong extensions Shift_JIS - Japanese EUC-JP - Japanese

Tips and Notes


Note: Unrecognized character-sets will be ignored and replaced by ISO-8859-1.

Example 1
<?php $str = "Jane &amp; &#039;Tarzan&#039;"; echo html_entity_decode($str); echo "<br />"; echo html_entity_decode($str, ENT_QUOTES); echo "<br />"; echo html_entity_decode($str, ENT_NOQUOTES); ?> The browser output of the code above will be: Jane & 'Tarzan' Jane & 'Tarzan' Jane & 'Tarzan' If you select "View source" in the browser window, you will see the following HTML: <html> <body> Jane & &#039;Tarzan&#039;<br /> Jane & 'Tarzan'<br /> Jane & &#039;Tarzan&#039; </body> </html>

Example 2
<html> <body> <?php $str = "My name is &Oslash;yvind &Aring;sane. I&#039;m Norwegian"; echo html_entity_decode($str, ENT_QUOTES, "ISO-8859-1"); ?>

Content Downloaded From www.w3schools.com

24

Created By www.ebooktutorials.blogspot.in
</body> </html> The browser output of the code above will be: My name is yvind sane. I'm Norwegian If you select "View source" in the browser window, you will see the following HTML: <html> <body> My name is yvind sane. I'm Norwegian </body> </html>

Content Downloaded From www.w3schools.com

25

Created By www.ebooktutorials.blogspot.in

PHP htmlentities() Function


Definition and Usage
The htmlentities() function converts characters to HTML entities.

Syntax
htmlentities(string,quotestyle,character-set) Parameter string quotestyle Description Required. Specifies the string to convert Optional. Specifies how to encode single and double quotes. The available quote styles are: ENT_COMPAT - Default. Encodes only double quotes ENT_QUOTES - Encodes double and single quotes ENT_NOQUOTES - Does not encode any quotes character-set Optional. A string that specifies which character-set to use. Allowed values are: ISO-8859-1 - Default. Western European ISO-8859-15 - Western European (adds the Euro sign + French and Finnish letters missing in ISO-88591) UTF-8 - ASCII compatible multi-byte 8-bit Unicode cp866 - DOS-specific Cyrillic charset cp1251 - Windows-specific Cyrillic charset cp1252 - Windows specific charset for Western European KOI8-R - Russian BIG5 - Traditional Chinese, mainly used in Taiwan GB2312 - Simplified Chinese, national standard character set BIG5-HKSCS - Big5 with Hong Kong extensions Shift_JIS - Japanese EUC-JP - Japanese

Tips and Notes


Note: Unrecognized character-sets will be ignored and replaced by ISO-8859-1.

Example 1
<html> <body> <?php $str = "Jane & 'Tarzan'"; echo htmlentities($str, ENT_COMPAT); echo "<br />"; echo htmlentities($str, ENT_QUOTES); echo "<br />"; echo htmlentities($str, ENT_NOQUOTES); ?> </body> </html> The browser output of the code above will be: Jane & 'Tarzan' Jane & 'Tarzan' Jane & 'Tarzan' If you select "View source" in the browser window, you will see the following HTML: <html> <body> Jane &amp; 'Tarzan'<br /> Jane &amp; &#039;Tarzan&#039;<br /> Jane &amp; 'Tarzan' </body> </html>

Example 2
<html> <body> <?php $str = "My name is yvind sane. I'm Norwegian";

Content Downloaded From www.w3schools.com

26

Created By www.ebooktutorials.blogspot.in
echo htmlentities($str, ENT_COMPAT, "ISO-8859-1"); ?> </body> </html> The browser output of the code above will be: My name is yvind sane. I'm Norwegian If you select "View source" in the browser window, you will see the following HTML: <html> <body> My name is &Oslash;yvind &Aring;sane. I'm Norwegian </body> </html>

Content Downloaded From www.w3schools.com

27

Created By www.ebooktutorials.blogspot.in

PHP htmlspecialchars_decode() Function


Definition and Usage
The htmlspecialchars_decode() function converts some predefined HTML entities to characters. HTML entities that will be decoded are: &amp; becomes & (ampersand) &quot; becomes " (double quote) &#039; becomes ' (single quote) &lt; becomes < (less than) &gt; becomes > (greater than) The htmlspecialchars_decode() function is the opposite of htmlspecialchars().

Syntax
htmlspecialchars_decode(string,quotestyle) Parameter string quotestyle Description Required. Specifies the string to decode Optional. Specifies how to decode single and double quotes. The available quote styles are: ENT_COMPAT - Default. Decodes only double quotes ENT_QUOTES - Decodes double and single quotes ENT_NOQUOTES - Does not decode any quotes

Example 1
<?php $str = "Jane &amp; &#039;Tarzan&#039;"; echo htmlspecialchars_decode($str); echo "<br />"; echo htmlspecialchars_decode($str, ENT_QUOTES); echo "<br />"; echo htmlspecialchars_decode($str, ENT_NOQUOTES); ?> The browser output of the code above will be: Jane & 'Tarzan' Jane & 'Tarzan' Jane & 'Tarzan' If you select "View source" in the browser window, you will see the following HTML: <html> <body> Jane & &#039;Tarzan&#039;<br /> Jane & 'Tarzan'<br /> Jane & &#039;Tarzan&#039; </body> </html>

Example 2
<html> <body> <?php $str = "My name is &Oslash;yvind &Aring;sane. I&#039;m Norwegian"; echo htmlspecialchars_decode($str, ENT_QUOTES); ?> </body> </html> The browser output of the code above will be: My name is yvind sane. I'm Norwegian If you select "View source" in the browser window, you will see the following HTML: <html> <body> My name is &Oslash;yvind &Aring;sane. I'm Norwegian </body> </html>

Content Downloaded From www.w3schools.com

28

Created By www.ebooktutorials.blogspot.in

PHP htmlspecialchars() Function


Definition and Usage
The htmlspecialchars() function converts some predefined characters to HTML entities. The predefined characters are: & (ampersand) becomes &amp; " (double quote) becomes &quot; ' (single quote) becomes &#039; < (less than) becomes &lt; > (greater than) becomes &gt;

Syntax
htmlspecialchars(string,quotestyle,character-set) Parameter string quotestyle Description Required. Specifies the string to convert Optional. Specifies how to encode single and double quotes. The available quote styles are: ENT_COMPAT - Default. Encodes only double quotes ENT_QUOTES - Encodes double and single quotes ENT_NOQUOTES - Does not encode any quotes character-set Optional. A string that specifies which character-set to use. Allowed values are: ISO-8859-1 - Default. Western European ISO-8859-15 - Western European (adds the Euro sign + French and Finnish letters missing in ISO-88591) UTF-8 - ASCII compatible multi-byte 8-bit Unicode cp866 - DOS-specific Cyrillic charset cp1251 - Windows-specific Cyrillic charset cp1252 - Windows specific charset for Western European KOI8-R - Russian BIG5 - Traditional Chinese, mainly used in Taiwan GB2312 - Simplified Chinese, national standard character set BIG5-HKSCS - Big5 with Hong Kong extensions Shift_JIS - Japanese EUC-JP - Japanese

Tips and Notes


Note: Unrecognized character-sets will be ignored and replaced by ISO-8859-1.

Example 1
<html> <body> <?php $str = "Jane & 'Tarzan'"; echo htmlspecialchars($str, ENT_COMPAT); echo "<br />"; echo htmlspecialchars($str, ENT_QUOTES); echo "<br />"; echo htmlspecialchars($str, ENT_NOQUOTES); ?> </body> </html> The browser output of the code above will be: Jane & 'Tarzan' Jane & 'Tarzan' Jane & 'Tarzan' If you select "View source" in the browser window, you will see the following HTML: <html> <body> Jane &amp; 'Tarzan'<br /> Jane &amp; &#039;Tarzan&#039;<br /> Jane &amp; 'Tarzan' </body> </html>

Content Downloaded From www.w3schools.com

29

Created By www.ebooktutorials.blogspot.in

PHP implode() Function


Definition and Usage
The implode() function returns a string from the elements of an array.

Syntax
implode(separator,array) Parameter separator array Description Optional. Specifies what to put between the array elements. Default is "" (an empty string) Required. The array to join to a string

Tips and Notes


Note: The implode() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments. Note: The separator parameter of implode() is optional. However, it is recommended to always use two parameters for backwards compatibility.

Example
<?php $arr = array('Hello','World!','Beautiful','Day!'); echo implode(" ",$arr); ?> The output of the code above will be: Hello World! Beautiful Day!

Content Downloaded From www.w3schools.com

30

Created By www.ebooktutorials.blogspot.in

PHP join() Function


Definition and Usage
The join() function returns a string from the elements of an array. The join() function is an alias of the implode() function.

Syntax
join(separator,array) Parameter separator array Description Optional. Specifies what to put between the array elements. Default is "" (an empty string) Required. The array to join to a string

Tips and Notes


Note: The join() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments. Note: The separator parameter of join() is optional. However, it is recommended to always use two parameters for backwards compatibility.

Example
<?php $arr = array('Hello','World!','Beautiful','Day!'); echo join(" ",$arr); ?> The output of the code above will be: Hello World! Beautiful Day!

Content Downloaded From www.w3schools.com

31

Created By www.ebooktutorials.blogspot.in

PHP levenshtein() Function


Definition and Usage
The levenshtein() function returns the Levenshtein distance between two strings. The Levenshtein distance is the number of characters you have to replace, insert or delete to transform string1 into string2. By default, PHP gives each operation (replace, insert, and delete) equal weight. However, you can define the cost of each operation by setting the optional insert, replace, and delete parameters.

Syntax
levenshtein(string1,string2,insert,replace,delete) Parameter string1 string2 insert replace delete Description Required. First string to compare Required. Second string to compare Optional. The cost of inserting a character. Default is 1 Optional. The cost of replacing a character. Default is 1 Optional. The cost of deleting a character. Default is 1

Tips and Notes


Note: The levenshtein() function returns -1 if one of the strings exceeds 255 characters. Note: The levenshtein() function is not case-sensitive. Note: The levenshtein() function is faster than the similar_text() function. However, similar_text() will give you a more accurate result with less modifications needed.

Example
<?php echo levenshtein("Hello World","ello World"); echo "<br />"; echo levenshtein("Hello World","ello World",10,20,30); ?> The output of the code above will be: 1 30

Content Downloaded From www.w3schools.com

32

Created By www.ebooktutorials.blogspot.in

PHP localeconv() Function


Definition and Usage
The localeconv() function returns an array containing local numeric and monetary formatting information. The localeconv() function will return the following array elements: [decimal_point] - Decimal point character [thousands_sep] - Thousands separator [int_curr_symbol] - Currency symbol (example: USD) [currency_symbol] - Currency symbol (example: $) [mon_decimal_point] - Monetary decimal point character [mon_thousands_sep] - Monetary thousands separator [positive_sign] - Positive value character [negative_sign] - Negative value character [int_frac_digits] - International fractional digits [frac_digits] - Local fractional digits [p_cs_precedes] - True (1) if currency symbol is placed in front of a positive value, False (0) if it is placed behind [p_sep_by_space] - True (1) if there is a spaces between the currency symbol and a positive value, False (0) otherwise [n_cs_precedes] - True (1) if currency symbol is placed in front of a negative value, False (0) if it is placed behind [n_sep_by_space] - True (1) if there is a spaces between the currency symbol and a negative value, False (0) otherwise [p_sign_posn] - Formatting options: 0 - Parentheses surround the quantity and currency symbol 1 - The + sign is placed in front of the quantity and currency symbol 2 - The + sign is placed after the quantity and currency symbol 3 - The + sign is placed immediately in front of the currency symbol 4 - The + sign is placed immediately after the currency symbol [n_sign_posn] - Formatting options: 0 - Parentheses surround the quantity and currency symbol 1 - The - sign is placed in front of the quantity and currency symbol 2 - The - sign is placed after the quantity and currency symbol 3 - The - sign is placed immediately in front of the currency symbol 4 - The - sign is placed immediately after the currency symbol [grouping] - Array displaying how numbers are grouped (example: 3 indicates 1 000 000) [mon_grouping] - Array displaying how monetary numbers are grouped (example: 2 indicates 1 00 00 00)

Syntax
localeconv()

Tips and Notes


Tip: To define locale settings, see the setlocale() function.

Example
In this example we will find the United States locale numeric formatting information: <?php setlocale(LC_ALL, 'US'); $locale_info = localeconv(); print_r($locale_info); ?> The output of the code above will be: Array ( [decimal_point] => . [thousands_sep] => , [int_curr_symbol] => USD [currency_symbol] => $ [mon_decimal_point] => . [mon_thousands_sep] => , [positive_sign] => [negative_sign] => [int_frac_digits] => 2 [frac_digits] => 2 [p_cs_precedes] => 1 [p_sep_by_space] => 0 [n_cs_precedes] => 1 [n_sep_by_space] => 0 [p_sign_posn] => 3 [n_sign_posn] => 0 [grouping] => Array ([0] => 3) [mon_grouping] => Array ([0] => 3) )

Content Downloaded From www.w3schools.com

33

Created By www.ebooktutorials.blogspot.in

PHP ltrim() Function


Definition and Usage
The ltrim() function will remove whitespaces or other predefined character from the left side of a string.

Syntax
ltrim(string,charlist) Parameter string charlist Description Required. Specifies the string to check Optional. Specifies which characters to remove from the string. If omitted, all of the following characters are removed: "\0" - NULL "\t" - tab "\n" - new line "\x0B" - vertical tab "\r" - carriage return " " - ordinary white space

Example 1
<html> <body> <?php $str = " Hello World!"; echo "Without ltrim: " . $str; echo "<br />"; echo "With ltrim: " . ltrim($str); ?> <body> <html> The browser output of the code above will be: Without ltrim: Hello World! With ltrim: Hello World! If you select "View source" in the browser window, you will see the following HTML: <html> <body> Without ltrim: </body> </html>

Hello World!<br />With ltrim: Hello World!

Example 2
<?php $str = "\r\nHello World!"; echo "Without ltrim: " . $str; echo "<br />"; echo "With ltrim: " . ltrim($str); ?> The browser output of the code above will be: Without ltrim: Hello World! With ltrim: Hello World! If you select "View source" in the browser window, you will see the following HTML: <html> <body> Without ltrim: Hello World!<br />With ltrim: Hello World! </body> </html>

Content Downloaded From www.w3schools.com

34

Created By www.ebooktutorials.blogspot.in

PHP md5() Function


Definition and Usage
The md5() function calculates the MD5 hash of a string. The md5() function uses the RSA Data Security, Inc. MD5 Message-Digest Algorithm. From RFC 1321 - The MD5 Message-Digest Algorithm: "The MD5 message-digest algorithm takes as input a message of arbitrary length and produces as output a 128-bit "fingerprint" or "message digest" of the input. The MD5 algorithm is intended for digital signature applications, where a large file must be "compressed" in a secure manner before being encrypted with a private (secret) key under a public-key cryptosystem such as RSA." This function returns the calculated MD5 hash on success, or FALSE on failure.

Syntax
md5(string,raw) Parameter Description string Required. The string to be calculated raw Optional. Specifies hex or binary output format: TRUE - Raw 16 character binary format FALSE - Default. 32 character hex number Note: This parameter was added in PHP 5.0

Example 1
<?php $str = "Hello"; echo md5($str); ?> The output of the code above will be: 8b1a9953c4611296a827abf8c47804d7

Example 2
In this example we will print the result of md5() and then test it: <?php $str = "Hello"; echo md5($str); if (md5($str) == '8b1a9953c4611296a827abf8c47804d7') { echo "<br />Hello world!"; exit; } ?> The output of the code above will be: 8b1a9953c4611296a827abf8c47804d7 Hello world!

Content Downloaded From www.w3schools.com

35

Created By www.ebooktutorials.blogspot.in

PHP md5_file() Function


Definition and Usage
The md5_file() function calculates the MD5 hash of a file. The md5_file() function uses the RSA Data Security, Inc. MD5 Message-Digest Algorithm. From RFC 1321 - The MD5 Message-Digest Algorithm: "The MD5 message-digest algorithm takes as input a message of arbitrary length and produces as output a 128-bit "fingerprint" or "message digest" of the input. The MD5 algorithm is intended for digital signature applications, where a large file must be "compressed" in a secure manner before being encrypted with a private (secret) key under a public-key cryptosystem such as RSA." This function returns the calculated MD5 hash on success, or FALSE on failure.

Syntax
md5_file(file,raw) Parameter Description file Required. The file to be calculated raw Optional. Specifies hex or binary output format: TRUE - Raw 16 character binary format FALSE - Default. 32 character hex number Note: This parameter was added in PHP 5.0

Example 1
<?php $filename = "test.txt"; $md5file = md5_file($filename); echo $md5file; ?> The output of the code above will be: 5d41402abc4b2a76b9719d911017c592

Example 2
Store the MD5 hash of "test.txt" in a file: <?php $md5file = md5_file("test.txt"); file_put_contents("md5file.txt",$md5file); ?> In this example we will test if "test.txt" has been changed (that is if the MD5 hash has been changed): <?php $md5file = file_get_contents("md5file.txt"); if (md5_file("test.txt") == $md5file) { echo "The file is ok."; } else { echo "The file has been changed."; } ?> The output of the code above could be: The file is ok.

Content Downloaded From www.w3schools.com

36

Created By www.ebooktutorials.blogspot.in

PHP metaphone() Function


Definition and Usage
The metaphone() function calculates the metaphone key of a string. A metaphone key represents how a string sounds if said by an English speaking person. The metaphone() function can be used for spelling applications. This function returns the metaphone key of the string on success, or FALSE on failure.

Syntax
metaphone(string,length) Parameter string length Description Required. Specifies the string to check Optional. Specifies the maximum length of the metaphone key

Tips and Notes


Note: The metaphone() function creates the same key for similar sounding words. Note: The generated metaphone keys vary in length. Tip: metaphone() is more accurate than the soundex() function, because metaphone() knows the basic rules of English pronunciation.

Example 1
<?php echo metaphone("world"); ?> The output of the code above will be: WRLT

Example 2
In this example we use the metaphone() function on two similar sounding words: <?php $str = "Sun"; $str2 = "Son"; echo metaphone($str); echo "<br />"; echo metaphone($str2); ?> The output of the code above will be: SN SN

Content Downloaded From www.w3schools.com

37

Created By www.ebooktutorials.blogspot.in

PHP money_format() Function


Definition and Usage
The money_format() function returns a string formatted as a currency string. This function inserts a formatted number where there is a percent (%) sign in the main string.

Syntax
money_format(string,number) Parameter string Description Required. Specifies the string to be formatted and how to format the variables in it. Possible format values: Padding and Flags: =f - Specifies the character (f) to be used as padding (Example: %=t this uses "t" as padding). Default is space ^ - Removes the use of grouping characters + or ( - Specifies how to show positive and negative numbers. If "+" is used, the local setting for + and will be used (usually a sign in front of negative numbers, and nothing in front of positive numbers). If "(" is used, negative numbers are enclosed in parenthesis. Default is "+" ! - Stops the use of currency symbols in the output string - If "-" is used, all fields are left-justified. Default is right-justified Field width:

x - Specifies the minimum field width (x). Default is 0 #x - Specifies the maximum number (x) of digits expected to the left of the decimal point. This is used to keep formatted output aligned in the same columns. If the number of digits are bigger than x, this specification is ignored .x - Specifies the maximum number (x) of digits expected to the right of the decimal point. If x is 0, the decimal point and the digits to it's right will not be shown. Default is local settings
Conversion characters: i - The number is formatted to international currency format n - The number is formatted to national currency format % - Returns the % character Note: If multiple format values are used, they must be in the same order as shown above. number Note: This function is affected by local settings. Required. The number to be inserted at the %-sign in the format string

Tips and Notes


Note: The money_format() function does not work on Windows platforms.

Example 1
International en_US format: <?php $number = 1234.56; setlocale(LC_MONETARY, "en_US"); echo money_format("The price is %i", $number); ?> The output of the code above will be: The price is USD 1,234.56

Example 2
National Norwegian format with 2 decimals: <?php $number = 1234.56; setlocale(LC_MONETARY, "no_NO"); echo money_format("%.2n", $number); ?> The output of the code above will be: NOK 1.234,56

Content Downloaded From www.w3schools.com

38

Created By www.ebooktutorials.blogspot.in

Example 3
Negative number, US national format with () to indicate negative numbers and 2 digits of right precision and "*" as fill character: <?php $number = -1234.5672; echo money_format("%=*(#10.2n", $number); ?> The output of the code above will be: ($********1,234.57)

Content Downloaded From www.w3schools.com

39

Created By www.ebooktutorials.blogspot.in

PHP nl_langinfo() Function


Definition and Usage
The nl_langinfo() function returns specific local information. This function returns the specific information on success, or FALSE on failure.

Syntax
nl_langinfo(element) Parameter element Description Required. Specifies which element to return. Must be one of the following elements: Time and Calendar: ABDAY_(1-7) - Abbreviated name of the numbered day of the week DAY_(1-7) - Name of the numbered day of the week (DAY_1 = Sunday) ABMON_(1-12) - Abbreviated name of the numbered month of the year MON_(1-12) - Name of the numbered month of the year AM_STR - String for Ante meridian PM_STR - String for Post meridian D_T_FMT - String that can be used as the format string for strftime() to represent time and date D_FMT - String that can be used as the format string for strftime() to represent date T_FMT - String that can be used as the format string for strftime() to represent time T_FMT_AMPM - String that can be used as the format string for strftime() to represent time in 12-hour format with ante/post meridian ERA - Alternate era ERA_YEAR - Year in alternate era format ERA_D_T_FMT - Date and time in alternate era format (string can be used in strftime()) ERA_D_FMT - Date in alternate era format (string can be used in strftime()) ERA_T_FMT - Time in alternate era format (string can be used in strftime()) Monetary Category: INT_CURR_SYMBOL - Currency symbol (example: USD) CURRENCY_SYMBOL - Currency symbol (example: $) CRNCYSTR - Same as CURRENCY_SYMBOL MON_DECIMAL_POINT - Monetary decimal point character MON_THOUSANDS_SEP - Monetary thousands separator POSITIVE_SIGN - Positive value character NEGATIVE_SIGN -Negative value character MON_GROUPING - Array displaying how monetary numbers are grouped (example: 1 000 000) INT_FRAC_DIGITS - International fractional digits FRAC_DIGITS - Local fractional digits P_CS_PRECEDES - True (1) if currency symbol is placed in front of a positive value, False (0) if it is placed behind P_SEP_BY_SPACE - True (1) if there is a spaces between the currency symbol and a positive value, False (0) otherwise N_CS_PRECEDES - True (1) if currency symbol is placed in front of a negative value, False (0) if it is placed behind N_SEP_BY_SPACE - True (1) if there is a spaces between the currency symbol and a negative value, False (0) otherwise P_SIGN_POSN - Formatting setting. Possible return values: 0 - Parentheses surround the quantity and currency symbol 1 - The sign string is placed in front of the quantity and currency symbol 2 - The sign string is placed after the quantity and currency symbol 3 - The sign string is placed immediately in front of the currency symbol 4 - The sign string is placed immediately after the currency symbol N_SIGN_POSN - Formatting setting. Possible return values: 0 - Parentheses surround the quantity and currency symbol 1 - The sign string is placed in front of the quantity and currency symbol 2 - The sign string is placed after the quantity and currency symbol 3 - The sign string is placed immediately in front of the currency symbol 4 - The sign string is placed immediately after the currency symbol Numeric Category: DECIMAL_POINT - Decimal point character RADIXCHAR - Same as DECIMAL_POINT THOUSANDS_SEP - Separator character for thousands THOUSEP - Same as THOUSANDS_SEP GROUPING - Array displaying how numbers are grouped (example: 1 000 000) Messaging Category: YESEXPR - Regex string for matching 'yes' input NOEXPR - Regex string for matching 'no' input YESSTR - Output string for 'yes' NOSTR - Output string for 'no' Code set Category: CODESET Return a string with the name of the character encoding.

Content Downloaded From www.w3schools.com

40

Created By www.ebooktutorials.blogspot.in

Tips and Notes


Note: This function does not work on Windows platforms. Tip: Unlike the localeconv() function, which returns all local formatting information, the nl_langinfo() function returns specific information.

Content Downloaded From www.w3schools.com

41

Created By www.ebooktutorials.blogspot.in

PHP nl2br() Function


Definition and Usage
The nl2br() function inserts HTML line breaks (<br />) in front of each newline (\n) in a string.

Syntax
nl2br(string) Parameter Description string Required. Specifies the string to check

Tips and Notes


Note: Before PHP 4.0.5, the nl2br() function inserted <br>. After PHP 4.0.5 it inserts the XHTML compliant <br />.

Example
<?php echo nl2br("One line.\nAnother line."); ?> The output of the code above will be: One line. Another line. The HTML source code will look like this: One line.<br /> Another line.

Content Downloaded From www.w3schools.com

42

Created By www.ebooktutorials.blogspot.in

PHP number_format() Function


Definition and Usage
The number_format() function formats a number with grouped thousands.

Syntax
number_format(number,decimals,decimalpoint,separator) Parameter number decimals decimalpoint separator Description Required. The number to be formatted. If no other parameters are set, the number will be formatted without decimals and with comma (,) as the thousands separator. Optional. Specifies how many decimals. If this parameter is set, the number will be formatted with a dot (.) as decimal point. Optional. Specifies what string to use for decimal point. Optional. Specifies what string to use for thousands separator. Only the first character of separator is used. For example, "xxx" will give the same output as "x". Note: If this parameter is given, all other parameters are required as well.

Tips and Notes


Note: This function supports one, two, or four parameters (not three).

Example
<?php echo number_format("1000000"); echo "<br />"; echo number_format("1000000",2); echo "<br />"; echo number_format("1000000",2,",","."); ?> The output of the code above will be: 1,000,000 1,000,000.00 1.000.000,00

Content Downloaded From www.w3schools.com

43

Created By www.ebooktutorials.blogspot.in

PHP ord() Function


Definition and Usage
The ord() function returns the ASCII value of the first character of a string.

Syntax
ord(string) Parameter Description string Required. The string to get an ASCII value from

Example
<?php echo ord("h")."<br />"; echo ord("hello")."<br />"; ?> The output of the code above will be: 104 104

Content Downloaded From www.w3schools.com

44

Created By www.ebooktutorials.blogspot.in

PHP parse_str() Function


Definition and Usage
The parse_str() function parses a query string into variables.

Syntax
parse_str(string,array) Parameter string array Description Required. Specifies the string to parse Optional. Specifies the name of an array to store the variables. This parameter indicates that the variables will be stored in an array. Note: This parameter was added in PHP 4.0.3

Tips and Notes


Note: If the array parameter is not set, variables set by this function will overwrite existing variables of the same name. Note: The magic_quotes_gpc setting in the php.ini file affects the output of this function. If enabled, the variables are converted by addslashes() before parsed by parse_str().

Example 1
<?php parse_str("id=23&name=Kai%20Jim"); echo $id."<br />"; echo $name; ?> The output of the code above will be: 23 Kai Jim

Example 2
<?php parse_str("id=23&name=Kai%20Jim",$myArray); print_r($myArray); ?> The output of the code above will be: Array ( [id] => 23 [name] => Kai Jim )

Content Downloaded From www.w3schools.com

45

Created By www.ebooktutorials.blogspot.in

PHP print() Function


Definition and Usage
The print() function outputs one or more strings.

Syntax
print(strings) Parameter strings Description Required. One or more strings to be sent to the output

Tips and Notes


Note: The print() function is not actually a function, so you are not required to use parentheses with it. Tip: The print() function is slightly slower than echo().

Example 1
<?php $str = "Who's Kai Jim?"; print $str; print "<br />"; print $str."<br />I don't know!"; ?> The output of the code above will be: Who's Kai Jim? Who's Kai Jim? I don't know!

Example 2
<?php print "This text spans multiple lines."; ?> The output of the code above will be: This text spans multiple lines.

Example 3
Difference of single and double quotes. Single quotes will print the variable name, not the value: <?php $color = "red"; print "Roses are $color"; print "<br />"; print 'Roses are $color'; ?> The output of the code above will be: Roses are red Roses are $color

Content Downloaded From www.w3schools.com

46

Created By www.ebooktutorials.blogspot.in

PHP printf() Function


Definition and Usage
The printf() function outputs a formatted string. The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc.

Syntax
printf(format,arg1,arg2,arg++) Parameter format Description Required. Specifies the string and how to format the variables in it. Possible format values: %% - Returns a percent sign %b - Binary number %c - The character according to the ASCII value %d - Signed decimal number %e - Scientific notation (e.g. 1.2e+2) %u - Unsigned decimal number %f - Floating-point number (local settings aware) %F - Floating-point number (not local settings aware) %o - Octal number %s - String %x - Hexadecimal number (lowercase letters) %X - Hexadecimal number (uppercase letters) Additional format values. These are placed between the % and the letter (example %.2f): + (Forces both + and - in front of numbers. By default, only negative numbers are marked) ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding) - (Left-justifies the variable value) [0-9] (Specifies the minimum width held of to the variable value) .[0-9] (Specifies the number of decimal digits or maximum string length) arg1 arg2 arg++ Note: If multiple additional format values are used, they must be in the same order as above. Required. The argument to be inserted at the first %-sign in the format string Optional. The argument to be inserted at the second %-sign in the format string Optional. The argument to be inserted at the third, fourth, etc. %-sign in the format string

Tips and Notes


Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "\$". See example three. Tip: Related functions: fprintf(), sprintf(), vfprintf(), vprintf(), and vsprintf().

Example 1
<?php $str = "Hello"; $number = 123; printf("%s world. Day number %u",$str,$number); ?> The output of the code above will be: Hello world. Day number 123

Example 2
<?php $number = 123; printf("%f",$number); ?> The output of the code above will be: 123.000000

Example 3
Content Downloaded From www.w3schools.com 47

Created By www.ebooktutorials.blogspot.in
Use of placeholders: <?php $number = 123; printf("With 2 decimals: %1\$.2f <br />With no decimals: %1\$u",$number); ?> The output of the code above will be: With 2 decimals: 123.00 With no decimals: 123

Content Downloaded From www.w3schools.com

48

Created By www.ebooktutorials.blogspot.in

PHP quoted_printable_decode() Function


Definition and Usage
The quoted_printable_decode() function decodes a quoted-printable string to an 8-bit ASCII string.

Syntax
quoted_printable_decode(string) Parameter string Description Required. Specifies the quoted-printable string to be decoded

Tips and Notes


Tip: Data encoded in quoted-printable are unlikely to be modified by mail transport. A text which is entirely US-ASCII may be encoded in quoted-printable to ensure the integrity of the data should the message pass through a character-translating, or line-wrapping gateway.

Example
<?php $str = "Hello=0Aworld."; echo quoted_printable_decode($str); ?> The output of the code above will be: Hello world. The HTML source of the code above will be: Hello world.

Content Downloaded From www.w3schools.com

49

Created By www.ebooktutorials.blogspot.in

PHP quotemeta() Function


Definition and Usage
The quotemeta() function adds backslashes in front of some predefined characters in a string. The predefined characters are: period (.) backslash (\) plus sign (+) asterisk (*) question mark (?) brackets ([]) caret (^) dollar sign ($) parenthesis (())

Syntax
quotemeta(string) Parameter Description string Required. Specifies the string to check

Tips and Notes


Tip: This function can be used to escape characters with special meanings, such as ( ), [ ], and * in SQL.

Example
<?php $str = "Hello world. (can you hear me?)"; echo quotemeta($str); ?> The output of the code above will be: Hello world\. \(can you hear me\?\)

Content Downloaded From www.w3schools.com

50

Created By www.ebooktutorials.blogspot.in

PHP rtrim() Function


Definition and Usage
The rtrim() function will remove whitespaces or other predefined character from the right side of a string.

Syntax
rtrim(string,charlist) Parameter string charlist Description Required. Specifies the string to check Optional. Specifies which characters to remove from the string. If omitted, all of the following characters are removed: "\0" - NULL "\t" - tab "\n" - new line "\x0B" - vertical tab "\r" - carriage return " " - ordinary white space

Example 1
<html> <body> <?php $str = "Hello World! "; echo "Without rtrim: " . $str; echo "<br />"; echo "With rtrim: " . rtrim($str); ?> <body> <html> The browser output of the code above will be: Without rtrim: Hello World! With rtrim: Hello World! If you select "View source" in the browser window, you will see the following HTML: <html> <body> Without rtrim: Hello World! </body> </html>

<br />With rtrim: Hello World!

Example 2
<?php $str = "Hello World!\r\n"; echo "Without rtrim: " . $str; echo "<br />"; echo "With rtrim: " . rtrim($str); ?> The browser output of the code above will be: Without rtrim: Hello World! With rtrim: Hello World! If you select "View source" in the browser window, you will see the following HTML: <html> <body> Without rtrim: Hello World! <br />With rtrim: Hello World! </body> </html>

Content Downloaded From www.w3schools.com

51

Created By www.ebooktutorials.blogspot.in

PHP setlocale() Function


Definition and Usage
The setlocale() function sets locale information. Locale information is language, monetary, time and other information specific for a geographical area. This function returns the current locale settings, or FALSE on failure.

Syntax
setlocale(constant,location) Parameter constant Description Required. Specifies what locale information should be set. Available constants: LC_ALL - All of the below LC_COLLATE - Sort order LC_CTYPE - Character classification and conversion (e.g. all characters should be lower or upper-case) LC_MESSAGES - System message formatting LC_MONETARY - Monetary/currency formatting LC_NUMERIC - Numeric formatting LC_TIME - Date and time formatting location Required. Specifies what country/region to set the locale information to. Can be a string or an array. If the location is an array, setlocale() will try each array element until it finds a valid language or region code. This is very useful if a region is known under different names on different systems. Note: To view all available language codes, go to our Language code reference.

Tips and Notes


Note: The setlocale() function changes the locale only for the current script. Tip: The locale information can be set to system default with setlocale(LC_ALL,NULL)

Example
In this example we will set the locale to US English and then back to default again: <?php echo setlocale(LC_ALL,"En-Us"); echo "<br />"; echo setlocale(LC_ALL,NULL); ?> The output of the code above will be: English_United States.1252 Norwegian (Bokml)_Norway.1252

Content Downloaded From www.w3schools.com

52

Created By www.ebooktutorials.blogspot.in

PHP sha1() Function


Definition and Usage
The sha1() function calculates the SHA-1 hash of a string. The sha1() function uses the US Secure Hash Algorithm 1. From RFC 3174 - The US Secure Hash Algorithm 1: "SHA-1 produces a 160-bit output called a message digest. The message digest can then, for example, be input to a signature algorithm which generates or verifies the signature for the message. Signing the message digest rather than the message often improves the efficiency of the process because the message digest is usually much smaller in size than the message. The same hash algorithm must be used by the verifier of a digital signature as was used by the creator of the digital signature." This function returns the calculated SHA-1 hash on success, or FALSE on failure.

Syntax
sha1(string,raw) Parameter Description string Required. The string to be calculated raw Optional. Specify hex or binary output format: TRUE - Raw 20 character binary format FALSE - Default. 40 character hex number Note: This parameter was added in PHP 5.0

Example 1
<?php $str = 'Hello'; echo sha1($str); ?> The output of the code above will be: f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0

Example 2
In this example we will print the result of sha1() and then test it: <?php $str = 'Hello'; echo sha1($str); if (sha1($str) == 'f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0') { echo "<br />Hello world!"; exit; } ?> The output of the code above will be: f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0 Hello world!

Content Downloaded From www.w3schools.com

53

Created By www.ebooktutorials.blogspot.in

PHP sha1_file() Function


Definition and Usage
The sha1_file() function calculates the SHA-1 hash of a file. The sha1_file() function uses the US Secure Hash Algorithm 1. From RFC 3174 - The US Secure Hash Algorithm 1: "SHA-1 produces a 160-bit output called a message digest. The message digest can then, for example, be input to a signature algorithm which generates or verifies the signature for the message. Signing the message digest rather than the message often improves the efficiency of the process because the message digest is usually much smaller in size than the message. The same hash algorithm must be used by the verifier of a digital signature as was used by the creator of the digital signature." This function returns the calculated SHA-1 hash on success, or FALSE on failure.

Syntax
sha1_file(file,raw) Parameter Description file Required. The file to be calculated raw Optional. Specifies hex or binary output format: TRUE - Raw 20 character binary format FALSE - Default. 40 character hex number Note: This parameter was added in PHP 5.0

Example 1
<?php $filename = "test.txt"; $sha1file = sha1_file($filename); echo $sha1file; ?> The output of the code above will be: aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d

Example 2
Store the SHA-1 hash of "test.txt" in a file: <?php $sha1file = sha1_file("test.txt"); file_put_contents("sha1file.txt",$sha1file); ?> In this example we will test if "test.txt" has been changed (that is if the SHA-1 hash has been changed): <?php $sha1file = file_get_contents("sha1file.txt"); if (sha1_file("test.txt") == $sha1file) { echo "The file is ok."; } else { echo "The file has been changed."; } ?> The output of the code above could be: The file is ok.

Content Downloaded From www.w3schools.com

54

Created By www.ebooktutorials.blogspot.in

PHP similar_text() Function


Definition and Usage
The similar_text() function returns the number of matching characters of two strings. It can also calculate the similarity of the two strings in percent.

Syntax
similar_text(string1,string2,percent) Parameter string1 string2 percent Description Required. Specifies the first string to be compared Required. Specifies the second string to be compared Optional. Specifies a variable name for storing the similarity in percent

Tips and Notes


Note: The levenshtein() function is faster than the similar_text() function. However, the similar_text() function will give you a more accurate result with less modifications needed.

Example 1
<?php echo similar_text("Hello World","Hello Peter"); ?> The output of the code above will be: 7

Example 2
<?php similar_text("Hello World","Hello Peter",$percent); echo $percent; ?> The output of the code above will be: 63.6363636364

Content Downloaded From www.w3schools.com

55

Created By www.ebooktutorials.blogspot.in

PHP soundex() Function


Definition and Usage
The soundex() function calculates the soundex key of a string. A soundex key is a four character long alphanumeric string that represent English pronunciation of a word. The soundex() function can be used for spelling applications. This function returns the soundex key of the string on success, or FALSE on failure.

Syntax
soundex(string) Parameter Description string Required. Specifies the string to check

Tips and Notes


Note: The soundex() function creates the same key for similar sounding words. Tip: metaphone() is more accurate than soundex(), because metaphone() knows the basic rules of English pronunciation.

Example 1
<?php $str = "hello"; echo soundex($str); ?> The output of the code above will be: H400

Example 2
In this example we use the soundex() function on two similar sounding words: <?php $str = "Sun"; $str2 = "Son"; echo soundex($str); echo "<br />"; echo soundex($str2); ?> The output of the code above will be: S500 S500

Content Downloaded From www.w3schools.com

56

Created By www.ebooktutorials.blogspot.in

PHP sprintf() Function


Definition and Usage
The sprintf() function writes a formatted string to a variable. The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc.

Syntax
sprintf(format,arg1,arg2,arg++) Parameter format Description Required. Specifies the string and how to format the variables in it. Possible format values: %% - Returns a percent sign %b - Binary number %c - The character according to the ASCII value %d - Signed decimal number %e - Scientific notation (e.g. 1.2e+2) %u - Unsigned decimal number %f - Floating-point number (local settings aware) %F - Floating-point number (not local settings aware) %o - Octal number %s - String %x - Hexadecimal number (lowercase letters) %X - Hexadecimal number (uppercase letters) Additional format values. These are placed between the % and the letter (example %.2f): + (Forces both + and - in front of numbers. By default, only negative numbers are marked) ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding) - (Left-justifies the variable value) [0-9] (Specifies the minimum width held of to the variable value) .[0-9] (Specifies the number of decimal digits or maximum string length) arg1 arg2 arg++ Note: If multiple additional format values are used, they must be in the same order as above. Required. The argument to be inserted at the first %-sign in the format string Optional. The argument to be inserted at the second %-sign in the format string Optional. The argument to be inserted at the third, fourth, etc. %-sign in the format string

Tips and Notes


Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "\$". See example three. Tip: Related functions: fprintf(), printf(), vfprintf(), vprintf(), and vsprintf().

Example 1
<?php $str = "Hello"; $number = 123; $txt = sprintf("%s world. Day number %u",$str,$number); echo $txt; ?> The output of the code above will be: Hello world. Day number 123

Example 2
<?php $number = 123; $txt = sprintf("%f",$number); echo $txt; ?> The output of the code above will be: 123.000000

Example 3
Content Downloaded From www.w3schools.com 57

Created By www.ebooktutorials.blogspot.in
Use of placeholders: <?php $number = 123; $txt = sprintf("With 2 decimals: %1\$.2f <br />With no decimals: %1\$u",$number); echo $txt; ?> The output of the code above will be: With 2 decimals: 123.00 With no decimals: 123

Content Downloaded From www.w3schools.com

58

Created By www.ebooktutorials.blogspot.in

PHP sscanf() Function


Definition and Usage
The sscanf() function parses input from a string according to a specified format. The sscanf() function parses a string into variables based on the format string. If only two parameters are passed to this function, the data will be returned as an array. Otherwise, if optional parameters are passed, the data parsed are stored in them. If there are more specifiers than variables to contain them, an error occurs. However, if there are less specifiers than variables, the extra variables contain NULL.

Syntax
sscanf(string,format,arg1,arg2,arg++) Parameter string format Description Required. Specifies the string to read Required. Specifies the format to use. Possible format values: %% - Returns a percent sign %b - Binary number %c - The character according to the ASCII value %d - Signed decimal number %e - Scientific notation (e.g. 1.2e+2) %u - Unsigned decimal number %f - Floating-point number (local settings aware) %F - Floating-point number (not local settings aware) %o - Octal number %s - String %x - Hexadecimal number (lowercase letters) %X - Hexadecimal number (uppercase letters) Additional format values. These are placed between the % and the letter (example %.2f): + (Forces both + and - in front of numbers. By default, only negative numbers are marked) ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding) - (Left-justifies the variable value) [0-9] (Specifies the minimum width held of to the variable value) .[0-9] (Specifies the number of decimal digits or maximum string length) arg1 arg2 arg++ Note: If multiple additional format values are used, they must be in the same order as above. Optional. The first variable to store data in Optional. The second variable to store data in Optional. The third, fourth, and so on, to store data in

Example 1
<?php $string = "age:30 weight:60kg"; sscanf($string,"age:%d weight:%dkg",$age,$weight); // show types and values var_dump($age,$weight); ?> The output of the code above will be: int(30) int(60)

Content Downloaded From www.w3schools.com

59

Created By www.ebooktutorials.blogspot.in

PHP str_ireplace() Function


Definition and Usage
The str_ireplace() function replaces some characters with some other characters in a string. This function works by the following rules: If If If If the string to be searched is an array, it returns an array the string to be searched is an array, find and replace is performed with every array element both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replace find is an array and replace is a string, the replace string will be used for every find value

Syntax
str_ireplace(find,replace,string,count) Parameter find replace string count Description Required. Specifies the value to find Required. Specifies the value to replace the value in find Required. Specifies the string to be searched Optional. A variable that counts the number of replacements

Tips and Notes


Note: This function is case-insensitive. Use str_replace() to perform a case-sensitive search. Note: This function is binary-safe.

Example 1
<?php echo str_ireplace("WORLD","Peter","Hello world!"); ?> The output of the code above will be: Hello Peter!

Example 2
In this example we will demonstrate str_ireplace() with an array and a count variable: <?php $arr = array("blue","red","green","yellow"); print_r(str_ireplace("RED","pink",$arr,$i)); echo "Replacements: $i"; ?> The output of the code above will be: Array ( [0] => blue [1] => pink [2] => green [3] => yellow ) Replacements: 1

Example 3
In this example we will demonstrate str_ireplace() with less elements in replace than find: <?php $find = array("HELLO","WORLD"); $replace = array("B"); $arr = array("Hello","world","!"); print_r(str_ireplace($find,$replace,$arr)); ?> The output of the code above will be: Array ( [0] => B

Content Downloaded From www.w3schools.com

60

Created By www.ebooktutorials.blogspot.in
[1] => [2] => ! )

Content Downloaded From www.w3schools.com

61

Created By www.ebooktutorials.blogspot.in

PHP str_pad() Function


Definition and Usage
The str_pad() function pads a string to a new length.

Syntax
str_pad(string,length,pad_string,pad_type) Parameter string length pad_string pad_type Description Required. Specifies the string to pad Required. Specifies the new string length. If this value is less than the original length of the string, nothing will be done Optional. Specifies the string to use for padding. Default is whitespace Optional. Specifies what side to pad the string. Possible values: STR_PAD_BOTH - Pad to both sides of the string. If not an even number, the right side gets the extra padding STR_PAD_LEFT - Pad to the left side of the string STR_PAD_RIGHT - Pad to the right side of the string. This is default

Example 1
<?php $str = "Hello World"; echo str_pad($str,20,"."); ?> The output of the code above will be: Hello World.........

Example 2
<?php $str = "Hello World"; echo str_pad($str,20,".",STR_PAD_LEFT); ?> The output of the code above will be: .........Hello World

Example 3
<?php $str = "Hello World"; echo str_pad($str,20,".:",STR_PAD_BOTH); ?> The output of the code above will be: .:.:Hello World.:.:.

Content Downloaded From www.w3schools.com

62

Created By www.ebooktutorials.blogspot.in

PHP str_repeat() Function


Definition and Usage
The str_repeat() function repeats a string a specified number of times.

Syntax
str_repeat(string,repeat) Parameter string repeat Description Required. Specifies the string to repeat Required. Specifies the number of times the string will be repeated. Must be greater or equal to 0

Example
<?php echo str_repeat(".",13); ?> The output of the code above will be: .............

Content Downloaded From www.w3schools.com

63

Created By www.ebooktutorials.blogspot.in

PHP str_replace() Function


Definition and Usage
The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If If If If the string to be searched is an array, it returns an array the string to be searched is an array, find and replace is performed with every array element both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replace find is an array and replace is a string, the replace string will be used for every find value

Syntax
str_replace(find,replace,string,count) Parameter find replace string count Description Required. Specifies the value to find Required. Specifies the value to replace the value in find Required. Specifies the string to be searched Optional. A variable that counts the number of replacements

Tips and Notes


Note: This function is case-sensitive. Use str_ireplace() to perform a case-insensitive search. Note: This function is binary-safe.

Example 1
<?php echo str_replace("world","Peter","Hello world!"); ?> The output of the code above will be: Hello Peter!

Example 2
In this example we will demonstrate str_replace() with an array and a count variable: <?php $arr = array("blue","red","green","yellow"); print_r(str_replace("red","pink",$arr,$i)); echo "Replacements: $i"; ?> The output of the code above will be: Array ( [0] => blue [1] => pink [2] => green [3] => yellow ) Replacements: 1

Example 3
In this example we will demonstrate str_replace() with less elements in replace than find: <?php $find = array("Hello","world"); $replace = array("B"); $arr = array("Hello","world","!"); print_r(str_replace($find,$replace,$arr)); ?> The output of the code above will be: Array ( [0] => B

Content Downloaded From www.w3schools.com

64

Created By www.ebooktutorials.blogspot.in
[1] => [2] => ! )

Content Downloaded From www.w3schools.com

65

Created By www.ebooktutorials.blogspot.in

PHP str_rot13() Function


Definition and Usage
The str_rot13() function performs the ROT13 encoding on a string. The ROT13 encoding shifts every letter 13 places in the alphabet. Numeric and non-alphabetical characters remains untouched.

Syntax
str_rot13(string) Parameter Description string Required. Specifies the string to encode

Tips and Notes


Tip: Encoding and decoding are done by the same function. If you pass an encoded string as argument, the original string will be returned.

Example
In this example we will encode and decode a string using the str_rot13() function: <?php echo str_rot13("Hello World"); echo "<br />"; echo str_rot13("Uryyb Jbeyq"); ?> The output of the code above will be: Uryyb Jbeyq Hello World

Content Downloaded From www.w3schools.com

66

Created By www.ebooktutorials.blogspot.in

PHP str_shuffle() Function


Definition and Usage
The str_shuffle() function randomly shuffles all the characters of a string.

Syntax
str_shuffle(string) Parameter Description string Required. Specifies the string to shuffle

Example
<?php echo str_shuffle("Hello World"); ?> The output of the code above could be: H leooWlrld

Content Downloaded From www.w3schools.com

67

Created By www.ebooktutorials.blogspot.in

PHP str_split() Function


Definition and Usage
The str_split() function splits a string into an array.

Syntax
str_split(string,length) Parameter string length Description Required. Specifies the string to split Optional. Specifies the length of each array element. Default is 1

Tips and Notes


Note: If length is less than 1, the str_split() function will return FALSE. Note: If length is larger than the length of string, the entire string will be returned as the only element of the array.

Example 1
<?php print_r(str_split("Hello")); ?> The output of the code above will be: Array ( [0] => [1] => [2] => [3] => [4] => )

H e l l o

Example 2
<?php print_r(str_split("Hello",3)); ?> The output of the code above will be: Array ( [0] => Hel [1] => lo )

Content Downloaded From www.w3schools.com

68

Created By www.ebooktutorials.blogspot.in

PHP str_word_count() Function


Definition and Usage
The str_word_count() function counts the number of words in a string.

Syntax
str_word_count(string,return,char) Parameter string return Description Required. Specifies the string to check Optional. Specifies the return value of the str_word_count() function. Possible values: 0 - Default. Returns the number of words found 1 - Returns an array with the words from the string 2 - Returns an array where the key is the position of the word in the string, and value is the actual word char Optional. Specifies special characters to be considered as words. Note: This parameter was added in PHP 5.1

Example 1
<?php echo str_word_count("Hello world!"); ?> The output of the code above will be: 2

Example 2
<?php print_r(str_word_count("Hello world!",1)); ?> The output of the code above will be: Array ( [0] => Hello [1] => world )

Example 3
<?php print_r(str_word_count("Hello world!",2)); ?> The output of the code above will be: Array ( [0] => Hello [6] => world )

Example 4
str_word_count() without and with the char parameter: <?php print_r(str_word_count("Hello world & good morning!",1)); print_r(str_word_count("Hello world & good morning!",1,"&")); ?> The output of the code above will be: Array ( [0] => Hello

Content Downloaded From www.w3schools.com

69

Created By www.ebooktutorials.blogspot.in
[1] => world [2] => good [3] => morning ) Array ( [0] => [1] => [2] => [3] => [4] => )

Hello world & good morning

Content Downloaded From www.w3schools.com

70

Created By www.ebooktutorials.blogspot.in

PHP strcasecmp() Function


Definition and Usage
The strcasecmp() function compares two strings. This function returns: 0 - if the two strings are equal <0 - if string1 is less than string2 >0 - if string1 is greater than string2

Syntax
strcasecmp(string1,string2) Parameter Description string1 Required. Specifies the first string to compare string2 Required. Specifies the second string to compare

Tips and Notes


Tip: The strcasecmp() function is binary safe and case-insensitive.

Example
<?php echo strcasecmp("Hello world!","HELLO WORLD!"); ?> The output of the code above will be: 0

Content Downloaded From www.w3schools.com

71

Created By www.ebooktutorials.blogspot.in

PHP strchr() Function


Definition and Usage
The strchr() function searches for the first occurrence of a string inside another string. This function returns the rest of the string (from the matching point), or FALSE, if the string to search for is not found. This function is an alias of the strstr() function.

Syntax
strchr(string,search) Parameter string search Description Required. Specifies the string to search Required. Specifies the string to search for. If this parameter is a number, it will search for the character matching the ASCII value of the number

Tips and Notes


Note: This function is binary safe. Note: This function is case-sensitive. For a case-insensitive search, use stristr().

Example 1
<?php echo strchr("Hello world!","world"); ?> The output of the code above will be: world!

Example 2
In this example we will search a string for the ASCII value of "o": <?php echo strchr("Hello world!",111); ?> The output of the code above will be: o world!

Content Downloaded From www.w3schools.com

72

Created By www.ebooktutorials.blogspot.in

PHP strcmp() Function


Definition and Usage
The strcmp() function compares two strings. This function returns: 0 - if the two strings are equal <0 - if string1 is less than string2 >0 - if string1 is greater than string2

Syntax
strcmp(string1,string2) Parameter Description string1 Required. Specifies the first string to compare string2 Required. Specifies the second string to compare

Tips and Notes


Note: The strcmp() function is binary safe and case-sensitive.

Example
<?php echo strcmp("Hello world!","Hello world!"); ?> The output of the code above will be: 0

Content Downloaded From www.w3schools.com

73

Created By www.ebooktutorials.blogspot.in

PHP strcoll() Function


Definition and Usage
The strcoll() function compares two strings. This function returns: 0 - if the two strings are equal <0 - if string1 is less than string2 >0 - if string1 is greater than string2 The comparison of the strings may vary depending on the locale settings (A<a or A>a).

Syntax
strcoll(string1,string2) Parameter Description string1 Required. Specifies the first string to compare string2 Required. Specifies the second string to compare

Tips and Notes


Note: The strcoll() is case-sensitive but not binary safe. Note: If the current locale is C or POSIX, this function works the same way as strcmp().

Example
<?php setlocale (LC_COLLATE, 'NL'); echo strcoll("Hello World!","Hello WORLD!"); echo "<br />"; setlocale (LC_COLLATE, 'en_US'); echo strcoll("Hello World!","Hello WORLD!"); ?> The output of the code above will be: -1 1

Content Downloaded From www.w3schools.com

74

Created By www.ebooktutorials.blogspot.in

PHP strcspn() Function


Definition and Usage
The strcspn() function returns the number of characters found in a string before any part of the specified characters are found.

Syntax
strcspn(string,char,start,length) Parameter string char start length Description Required. Specifies the string to search Required. Specifies the characters to search for Optional. Specifies where in string to start Note: This parameter was added in PHP 4.3 Optional. Specifies the length of the string (how much of the string to search) Note: This parameter was added in PHP 4.3

Tips and Notes


Note: This function is binary safe.

Example
<?php echo strcspn("Hello world!","w"); ?> The output of the code above will be: 6

Content Downloaded From www.w3schools.com

75

Created By www.ebooktutorials.blogspot.in

PHP strip_tags() Function


Definition and Usage
The strip_tags() function strips a string from HTML, XML, and PHP tags.

Syntax
strip_tags(string,allow) Parameter string allow Description Required. Specifies the string to check Optional. Specifies allowable tags. These tags will not be removed

Tips and Notes


Note: HTML comments are always stripped. This cannot be changed with the allow parameter.

Example 1
<?php echo strip_tags("Hello <b>world!</b>"); ?> The output of the code above will be: Hello world!

Example 2
<?php echo strip_tags("Hello <b><i>world!</i></b>","<b>"); ?> The output of the code above will be: Hello world!

Content Downloaded From www.w3schools.com

76

Created By www.ebooktutorials.blogspot.in

PHP stripcslashes() Function


Definition and Usage
The stripcslashes() function removes backslashes added by the addcslashes() function.

Syntax
stripcslashes(string) Parameter Description string Required. Specifies the string to check

Tips and Notes


Tip: This function can be used to clean up a string retrieved from a database.

Example
<?php echo stripcslashes("Hello, \my na\me is Kai Ji\m."); ?> The output of the code above will be: Hello, my name is Kai Jim.

Content Downloaded From www.w3schools.com

77

Created By www.ebooktutorials.blogspot.in

PHP stripslashes() Function


Definition and Usage
The stripslashes() function removes backslashes added by the addslashes() function.

Syntax
stripslashes(string) Parameter Description string Required. Specifies the string to check

Tips and Notes


Tip: This function can be used to clean up data retrieved from a database or from an HTML form.

Example
<?php echo stripslashes("Who\'s Kai Jim?"); ?> The output of the code above will be: Who's Kai Jim?

Content Downloaded From www.w3schools.com

78

Created By www.ebooktutorials.blogspot.in

PHP stripos() Function


Definition and Usage
The stripos() function returns the position of the first occurrence of a string inside another string. If the string is not found, this function returns FALSE.

Syntax
stripos(string,find,start) Parameter Description string Required. Specifies the string to search find Required. Specifies the string to find start Optional. Specifies where to begin the search

Tips and Notes


Note: The stripos() function is case-insensitive.

Example
<?php echo stripos("Hello world!","WO"); ?> The output of the code above will be: 6

Content Downloaded From www.w3schools.com

79

Created By www.ebooktutorials.blogspot.in

PHP stristr() Function


Definition and Usage
The stristr() function searches for the first occurrence of a string inside another string. This function returns the rest of the string (from the matching point), or FALSE, if the string to search for is not found.

Syntax
stristr(string,search) Parameter string search Description Required. Specifies the string to search Required. Specifies the string to search for. If this parameter is a number, it will search for the character matching the ASCII value of the number

Tips and Notes


Note: This function is binary safe. Note: This function is case-insensitive. For a case-sensitive search, use strstr().

Example 1
<?php echo stristr("Hello world!","WORLD"); ?> The output of the code above will be: world!

Example 2
In this example we will search a string for the ASCII value of "o": <?php echo stristr("Hello world!",111); ?> The output of the code above will be: o world!

Content Downloaded From www.w3schools.com

80

Created By www.ebooktutorials.blogspot.in

PHP strlen() Function


Definition and Usage
The strlen() function returns the length of a string.

Syntax
strlen(string) Parameter Description string Required. Specifies the string to check

Example
<?php echo strlen("Hello world!"); ?> The output of the code above will be: 12

Content Downloaded From www.w3schools.com

81

Created By www.ebooktutorials.blogspot.in

PHP strnatcasecmp() Function


Definition and Usage
The strnatcasecmp() function compares two strings using a "natural" algorithm. In a natural algorithm, the number 2 is less than the number 10. In computer sorting, 10 is less than 2, because the first number in "10" is less than 2. This function returns: 0 - if the two strings are equal <0 - if string1 is less than string2 >0 - if string1 is greater than string2

Syntax
strnatcasecmp(string1,string2) Parameter Description string1 Required. Specifies the first string to compare string2 Required. Specifies the second string to compare

Tips and Notes


Note: The strnatcasecmp() is case-insensitive.

Example
<?php echo strnatcasecmp("2Hello world!","10Hello world!"); echo "<br />"; echo strnatcasecmp("10Hello world!","2Hello world!"); ?> The output of the code above will be: -1 1

Content Downloaded From www.w3schools.com

82

Created By www.ebooktutorials.blogspot.in

PHP strnatcmp() Function


Definition and Usage
The strnatcmp() function compares two strings using a "natural" algorithm. In a natural algorithm, the number 2 is less than the number 10. In computer sorting, 10 is less than 2, because the first number in "10" is less than 2. This function returns: 0 - if the two strings are equal <0 - if string1 is less than string2 >0 - if string1 is greater than string2

Syntax
strnatcmp(string1,string2) Parameter Description string1 Required. Specifies the first string to compare string2 Required. Specifies the second string to compare

Tips and Notes


Note: The strnatcmp() is case-sensitive.

Example
<?php echo strnatcmp("2Hello world!","10Hello world!"); echo "<br />"; echo strnatcmp("10Hello world!","2Hello world!"); ?> The output of the code above will be: -1 1

Content Downloaded From www.w3schools.com

83

Created By www.ebooktutorials.blogspot.in

PHP strncasecmp() Function


Definition and Usage
The strncasecmp() function compares two strings. This function returns: 0 - if the two strings are equal <0 - if string1 is less than string2 >0 - if string1 is greater than string2

Syntax
strncasecmp(string1,string2,length) Parameter string1 string2 length Description Required. Specifies the first string to compare Required. Specifies the second string to compare Required. Specify the number of characters from each string to be used in the comparison

Tips and Notes


Note: The strncasecmp() is binary safe and case-insensitive.

Example
<?php echo strncasecmp("Hello world!","hello earth!",6); ?> The output of the code above will be: 0

Content Downloaded From www.w3schools.com

84

Created By www.ebooktutorials.blogspot.in

PHP strncmp() Function


Definition and Usage
The strncmp() function compares two strings. This function returns: 0 - if the two strings are equal <0 - if string1 is less than string2 >0 - if string1 is greater than string2

Syntax
strncmp(string1,string2,length) Parameter string1 string2 length Description Required. Specifies the first string to compare Required. Specifies the second string to compare Required. Specify the number of characters from each string to be used in the comparison

Tips and Notes


Note: The strncmp() is binary safe and case-sensitive.

Example
<?php echo strncmp("Hello world!","Hello earth!",6); ?> The output of the code above will be: 0

Content Downloaded From www.w3schools.com

85

Created By www.ebooktutorials.blogspot.in

PHP strpbrk() Function


Definition and Usage
The strpbrk() function searches a string for any of the specified characters. This function returns the rest of the string from where it found the first occurrence of a specified character, otherwise it returns FALSE.

Syntax
strpbrk(string,charlist) Parameter Description string Required. Specifies the string to search charlist Required. Specifies the characters to find

Tips and Notes


Note: This function is case-sensitive.

Example
<?php echo strpbrk("Hello world!","oe"); ?> The output of the code above will be: ello world!

Content Downloaded From www.w3schools.com

86

Created By www.ebooktutorials.blogspot.in

PHP strpos() Function


Definition and Usage
The strpos() function returns the position of the first occurrence of a string inside another string. If the string is not found, this function returns FALSE.

Syntax
strpos(string,find,start) Parameter Description string Required. Specifies the string to search find Required. Specifies the string to find start Optional. Specifies where to begin the search

Tips and Notes


Note: The strpos() function is case-sensitive.

Example
<?php echo strpos("Hello world!","wo"); ?> The output of the code above will be: 6

Content Downloaded From www.w3schools.com

87

Created By www.ebooktutorials.blogspot.in

PHP strrchr() Function


Definition and Usage
The strrchr() function finds the position of the last occurrence of a string within another string, and returns all characters from this position to the end of the string. If char cannot be found, this function returns FALSE.

Syntax
strrchr(string,char) Parameter string char Description Required. Specifies the string to search Required. Specifies the string to find. If this is a number, it will search for the character matching the ASCII value of that number

Tips and Notes


Tip: This function is binary safe.

Example 1
<?php echo strrchr("Hello world!","world"); ?> The output of the code above will be: world!

Example 2
In this example we will search a string for the ASCII value of "o": <?php echo strrchr("Hello world!",111); ?> The output of the code above will be: orld!

Content Downloaded From www.w3schools.com

88

Created By www.ebooktutorials.blogspot.in

PHP strrev() Function


Definition and Usage
The strrev() function reverses a string.

Syntax
strrev(string) Parameter Description string Required. Specifies the string to reverse

Example
<?php echo strrev("Hello World!"); ?> The output of the code above will be: !dlroW olleH

Content Downloaded From www.w3schools.com

89

Created By www.ebooktutorials.blogspot.in

PHP strripos() Function


Definition and Usage
The strripos() function finds the position of the last occurrence of a string inside another string. This function returns the position on success, otherwise it returns FALSE.

Syntax
strripos(string,find,start) Parameter Description string Required. Specifies the string to search find Required. Specifies the string to find start Optional. Specifies where to begin the search

Tips and Notes


Note: The strripos() function is case-insensitive.

Example
<?php echo strripos("Hello world!","WO"); ?> The output of the code above will be: 6

Content Downloaded From www.w3schools.com

90

Created By www.ebooktutorials.blogspot.in

PHP strrpos() Function


Definition and Usage
The strrpos() function finds the position of the last occurrence of a string inside another string. This function returns the position on success, otherwise it returns FALSE.

Syntax
strrpos(string,find,start) Parameter Description string Required. Specifies the string to search find Required. Specifies the string to find start Optional. Specifies where to begin the search

Tips and Notes


Note: The strrpos() function is case-sensitive.

Example
<?php echo strrpos("Hello world!","wo"); ?> The output of the code above will be: 6

Content Downloaded From www.w3schools.com

91

Created By www.ebooktutorials.blogspot.in

PHP strspn() Function


Definition and Usage
The strspn() function returns the number of characters found in the string that contains only characters from the charlist.

Syntax
strspn(string,charlist,start,length) Parameter Description string Required. Specifies the string to search charlist Required. Specifies the characters to find start Optional. Specifies where in the string to start length Optional. Defines the length of the string

Tips and Notes


Note: This function is binary safe.

Example 1
<?php echo strspn("Hello world!","kHlleo"); ?> The output of the code above will be: 5

Example 2
<?php echo strspn("abcdefand","abc"); ?> The output of the code above will be: 3

Content Downloaded From www.w3schools.com

92

Created By www.ebooktutorials.blogspot.in

PHP strstr() Function


Definition and Usage
The strstr() function searches for the first occurrence of a string inside another string. This function returns the rest of the string (from the matching point), or FALSE, if the string to search for is not found.

Syntax
strstr(string,search) Parameter string search Description Required. Specifies the string to search Required. Specifies the string to search for. If this parameter is a number, it will search for the character matching the ASCII value of the number

Tips and Notes


Note: This function is binary safe. Note: This function is case-sensitive. For a case-insensitive search, use stristr().

Example 1
<?php echo strstr("Hello world!","world"); ?> The output of the code above will be: world!

Example 2
In this example we will search a string for the ASCII value of "o": <?php echo strstr("Hello world!",111); ?> The output of the code above will be: o world!

Content Downloaded From www.w3schools.com

93

Created By www.ebooktutorials.blogspot.in

PHP strtok() Function


Definition and Usage
The strtok() function splits a string into smaller strings.

Syntax
strtok(string,split) Parameter Description string Required. Specifies the string to split split Required. Specifies one or more split characters

Example
In the example below, note that it is only the first call to strtok() that uses the string argument. After the first call, this function only needs the split argument, as it keeps track of where it is in the current string. To tokenize a new string, call strtok() with the string argument again: <?php $string = "Hello world. Beautiful day today."; $token = strtok($string, " "); while ($token != false) { echo "$token<br />"; $token = strtok(" "); } ?> The output of the code above will be: Hello world. Beautiful day today.

Content Downloaded From www.w3schools.com

94

Created By www.ebooktutorials.blogspot.in

PHP strtolower() Function


Definition and Usage
The strtolower() function converts a string to lowercase.

Syntax
strtolower(string) Parameter Description string Required. Specifies the string to convert

Example
<?php echo strtolower("Hello WORLD."); ?> The output of the code above will be: hello world.

Content Downloaded From www.w3schools.com

95

Created By www.ebooktutorials.blogspot.in

PHP strtoupper() Function


Definition and Usage
The strtoupper() function converts a string to uppercase.

Syntax
strtoupper(string) Parameter Description string Required. Specifies the string to convert

Example
<?php echo strtoupper("Hello WORLD!"); ?> The output of the code above will be: HELLO WORLD!

Content Downloaded From www.w3schools.com

96

Created By www.ebooktutorials.blogspot.in

PHP strtr() Function


Definition and Usage
The strtr() function translates certain characters in a string.

Syntax
strtr(string,from,to) or strtr(string,array) Parameter string from to array Description Required. Specifies the string to translate Required (unless array is used). Specifies what characters to change Required (unless array is used). Specifies what characters to change into Required (unless to and from is used). An array containing what to change from as key, and what to change to as value

Tips and Notes


Note: If from and to are different length, both will be formatted to the length of the shortest.

Example 1
<?php echo strtr("Hilla Warld","ia","eo"); ?> The output of the code above will be: Hello World

Example 2
<?php $arr = array("Hello" => "Hi", "world" => "earth"); echo strtr("Hello world",$arr); ?> The output of the code above will be: Hi earth

Content Downloaded From www.w3schools.com

97

Created By www.ebooktutorials.blogspot.in

PHP substr() Function


Definition and Usage
The substr() function returns a part of a string.

Syntax
substr(string,start,length) Parameter string start Description Required. Specifies the string to return a part of Required. Specifies where to start in the string A positive number - Start at a specified position in the string A negative number - Start at a specified position from the end of the string 0 - Start at the first character in string length Optional. Specifies the length of the returned string. Default is to the end of the string. A positive number - The length to be returned from the start parameter Negative number - The length to be returned from the end of the string

Tips and Notes


Note: If start is a negative number and length is less than or equal to start, length becomes 0.

Example 1
<?php echo substr("Hello world!",6); ?> The output of the code above will be: world!

Example 2
<?php echo substr("Hello world!",6,5); ?> The output of the code above will be: world

Content Downloaded From www.w3schools.com

98

Created By www.ebooktutorials.blogspot.in

PHP substr_compare() Function


Definition and Usage
The substr_compare() function compares two strings from a specified start position. This function returns: 0 - if the two strings are equal <0 - if string1 (from startpos) is less than string2 >0 - if string1 (from startpos) is greater than string2 If length is equal or greater than length of string1, this function returns FALSE.

Syntax
substr_compare(string1,string2,startpos,length,case) Parameter string1 string2 startpos length case Description Required. Specifies the first string to compare Required. Specifies the second string to compare Required. Specifies where to start comparing in string1 Optional. Specifies how much of string1 to compare Optional. Specifies whether or not to perform a case-sensitive compare. Default is FALSE (case-sensitive)

Tips and Notes


Tip: This function is binary safe and optionally case-sensitive.

Example 1
<?php echo substr_compare("Hello world","Hello world",0); ?> The output of the code above will be: 0

Example 2
<?php echo substr_compare("Hello world","world",6); ?> The output of the code above will be: 0

Example 3
<?php echo substr_compare("Hello world","WORLD",6,TRUE); ?> The output of the code above will be: 0

Content Downloaded From www.w3schools.com

99

Created By www.ebooktutorials.blogspot.in

PHP substr_count() Function


Definition and Usage
The substr_count() function counts the number of times a substring occurs in a string.

Syntax
substr_count(string,substring,start,length) Parameter string substring start length Description Required. Specifies the string to check Required. Specifies the string to search for Optional. Specifies where in string to start searching Optional. Specifies the length of the search

Example
<?php echo substr_count("Hello world. The world is nice","world"); ?> The output of the code above will be: 2

Content Downloaded From www.w3schools.com

100

Created By www.ebooktutorials.blogspot.in

PHP substr_replace() Function


Definition and Usage
The substr_replace() function replaces a part of a string with another string.

Syntax
substr_replace(string,replacement,start,length) Parameter string replacement start Description Required. Specifies the string to check Required. Specifies the string to insert Required. Specifies where to start replacing in the string A positive number - Start replacing at the specified position in the string Negative number - Start replacing at the specified position from the end of the string 0 - Start replacing at the first character in the string length Optional. Specifies how many characters should be replaced. Default is the same length as the string. A positive number - The length of string to be replaced A negative number - How many characters should be left at end of string after replacing 0 - Insert instead of replace

Tips and Notes


Note: If start is a negative number and length is less than or equal to start, length becomes 0.

Example
<?php echo substr_replace("Hello world","earth",6); ?> The output of the code above will be: Hello earth

Content Downloaded From www.w3schools.com

101

Created By www.ebooktutorials.blogspot.in

PHP trim() Function


Definition and Usage
The trim() function removes whitespaces and other predefined characters from both sides of a string.

Syntax
trim(string,charlist) Parameter string charlist Description Required. Specifies the string to check Optional. Specifies which characters to remove from the string. If omitted, all of the following characters are removed: "\0" - NULL "\t" - tab "\n" - new line "\x0B" - vertical tab "\r" - carriage return " " - ordinary white space

Example 1
<html> <body> <?php $str = " Hello World! "; echo "Without trim: " . $str; echo "<br />"; echo "With trim: " . trim($str); ?> <body> <html> The browser output of the code above will be: Without trim: Hello World! With trim: Hello World! If you select "View source" in the browser window, you will see the following HTML: <html> <body> Without trim: Hello World! <br /> With trim: Hello World! </body> </html>

Example 2
<?php $str = "\r\nHello World!\r\n"; echo "Without trim: " . $str; echo "<br />"; echo "With trim: " . trim($str); ?> The browser output of the code above will be: Without trim: Hello World! With trim: Hello World! If you select "View source" in the browser window, you will see the following HTML: <html> <body> Without trim: Hello World! <br />With trim: Hello World! </body> </html>

Content Downloaded From www.w3schools.com

102

Created By www.ebooktutorials.blogspot.in

P HP ucfirst() Function
Definition and Usage
The ucfirst() function converts the first character of a string to uppercase.

Syntax
ucfirst(string) Parameter Description string Required. Specifies the string to convert

Example
<?php echo ucfirst("hello world"); ?> The output of the code above will be: Hello world

Content Downloaded From www.w3schools.com

103

Created By www.ebooktutorials.blogspot.in

PHP ucwords() Function


Definition and Usage
The ucwords() function converts the first character of each word in a string to uppercase.

Syntax
ucwords(string) Parameter Description string Required. Specifies the string to convert

Example
<?php echo ucwords("hello world"); ?> The output of the code above will be: Hello World

Content Downloaded From www.w3schools.com

104

Created By www.ebooktutorials.blogspot.in

PHP vfprintf() Function


Definition and Usage
The vfprintf() function writes a formatted string to a specified output stream (example: file or database). Unlike fprintf(), the arguments in vfprintf(), are placed in an array. The array elements will be inserted at the percent (%) signs in the main string. This function works "step-by-step". At the first % sign, the first array element is inserted, at the second % sign, the second array element is inserted, etc. The vfprintf() function returns the length of the written string.

Syntax
vfprintf(stream,format,argarray) Parameter stream format Description Required. Specifies where to write/output the string Required. Specifies the string and how to format the variables in it. Possible format values: %% - Returns a percent sign %b - Binary number %c - The character according to the ASCII value %d - Signed decimal number %e - Scientific notation (e.g. 1.2e+2) %u - Unsigned decimal number %f - Floating-point number (local settings aware) %F - Floating-point number (not local settings aware) %o - Octal number %s - String %x - Hexadecimal number (lowercase letters) %X - Hexadecimal number (uppercase letters) Additional format values. These are placed between the % and the letter (example %.2f): + (Forces both + and - in front of numbers. By default, only negative numbers are marked) ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding) - (Left-justifies the variable value) [0-9] (Specifies the minimum width held of to the variable value) .[0-9] (Specifies the number of decimal digits or maximum string length) argarray Note: If multiple additional format values are used, they must be in the same order as above. Required. An array with arguments to be inserted at the % signs in the format string

Tips and Notes


Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "\$". See example three. Tip: Related functions: fprintf(), printf(), sprintf(), vprintf(), and vsprintf().

Example 1
<?php $str = "Hello"; $number = 123; $file = fopen("test.txt","w"); echo vfprintf($file,"%s world. Day number %u",array($str,$number)); ?> The output of the code above will be: 27 The following text will be written to the file "test.txt": Hello world. Day number 123

Example 2
<?php $num1 = 123; $num2 = 456; $file = fopen("test.txt","w"); vfprintf($file,"%f%f",array($num1,$num2)); ?>

Content Downloaded From www.w3schools.com

105

Created By www.ebooktutorials.blogspot.in
The following text will be written to the file "test.txt": 123.000000456.000000

Example 3
Use of placeholders: <?php $number = 123; $file = fopen("test.txt","w"); vfprintf($file,"With 2 decimals: %1\$.2f \nWith no decimals: %1\$u",array($number)); ?> The following text will be written to the file "test.txt": With 2 decimals: 123.00 With no decimals: 123

Content Downloaded From www.w3schools.com

106

Created By www.ebooktutorials.blogspot.in

PHP vprintf() Function


Definition and Usage
The vprintf() function outputs a formatted string. Unlike printf(), the arguments in vprintf(), are placed in an array. The array elements will be inserted at the percent (%) signs in the main string. This function works "step-by-step". At the first % sign, the first array element is inserted, at the second % sign, the second array element is inserted, etc.

Syntax
vprintf(format,argarray) Parameter format Description Required. Specifies the string and how to format the variables in it. Possible format values: %% - Returns a percent sign %b - Binary number %c - The character according to the ASCII value %d - Signed decimal number %e - Scientific notation (e.g. 1.2e+2) %u - Unsigned decimal number %f - Floating-point number (local settings aware) %F - Floating-point number (not local settings aware) %o - Octal number %s - String %x - Hexadecimal number (lowercase letters) %X - Hexadecimal number (uppercase letters) Additional format values. These are placed between the % and the letter (example %.2f): + (Forces both + and - in front of numbers. By default, only negative numbers are marked) ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding) - (Left-justifies the variable value) [0-9] (Specifies the minimum width held of to the variable value) .[0-9] (Specifies the number of decimal digits or maximum string length) argarray Note: If multiple additional format values are used, they must be in the same order as above. Required. An array with arguments to be inserted at the % signs in the format string

Tips and Notes


Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "\$". See example three. Tip: Related functions: fprintf(), printf(), sprintf(), vfprintf(), and vsprintf().

Example 1
<?php $str = "Hello"; $number = 123; vprintf("%s world. Day number %u",array($str,$number)); ?> The output of the code above will be: Hello world. Day number 123

Example 2
<?php $num1 = 123; $num2 = 456; vprintf("%f%f",array($num1,$num2)); ?> The output of the code above will be: 123.000000456.000000

Example 3
Use of placeholders:

Content Downloaded From www.w3schools.com

107

Created By www.ebooktutorials.blogspot.in
<?php $number = 123; vprintf("With 2 decimals: %1\$.2f <br />With no decimals: %1\$u",array($number)); ?> The output of the code above will be: With 2 decimals: 123.00 With no decimals: 123

Content Downloaded From www.w3schools.com

108

Created By www.ebooktutorials.blogspot.in

PHP vsprintf() Function


Definition and Usage
The vsprintf() function writes a formatted string to a variable. Unlike sprintf(), the arguments in vsprintf(), are placed in an array. The array elements will be inserted at the percent (%) signs in the main string. This function works "step-by-step". At the first % sign, the first array element is inserted, at the second % sign, the second array element is inserted, etc.

Syntax
vsprintf(format,argarray) Parameter format Description Required. Specifies the string and how to format the variables in it. Possible format values: %% - Returns a percent sign %b - Binary number %c - The character according to the ASCII value %d - Signed decimal number %e - Scientific notation (e.g. 1.2e+2) %u - Unsigned decimal number %f - Floating-point number (local settings aware) %F - Floating-point number (not local settings aware) %o - Octal number %s - String %x - Hexadecimal number (lowercase letters) %X - Hexadecimal number (uppercase letters) Additional format values. These are placed between the % and the letter (example %.2f): + (Forces both + and - in front of numbers. By default, only negative numbers are marked) ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding) - (Left-justifies the variable value) [0-9] (Specifies the minimum width held of to the variable value) .[0-9] (Specifies the number of decimal digits or maximum string length) argarray Note: If multiple additional format values are used, they must be in the same order as above. Required. An array with arguments to be inserted at the % signs in the format string

Tips and Notes


Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "\$". See example three. Tip: Related functions: fprintf(), printf(), sprintf(), vfprintf(), and vprintf().

Example 1
<?php $str = "Hello"; $number = 123; $txt = vsprintf("%s world. Day number %u",array($str,$number)); echo $txt; ?> The output of the code above will be: Hello world. Day number 123

Example 2
<?php $num1 = 123; $num2 = 456; $txt = vsprintf("%f%f",array($num1,$num2)); echo $txt; ?> The output of the code above will be: 123.000000456.000000

Example 3
Content Downloaded From www.w3schools.com 109

Created By www.ebooktutorials.blogspot.in
Use of placeholders: <?php $number = 123; $txt = vsprintf("With 2 decimals: %1\$.2f <br />With no decimals: %1\$u",array($number)); echo $txt; ?> The output of the code above will be: With 2 decimals: 123.00 With no decimals: 123

Content Downloaded From www.w3schools.com

110

Created By www.ebooktutorials.blogspot.in

PHP wordwrap() Function


Definition and Usage
The wordwrap() function wraps a string into new lines when it reaches a specific length. This function returns the string broken into lines on success, or FALSE on failure.

Syntax
wordwrap(string,width,break,cut) Parameter string width break cut Description Required. Specifies the string to break up into lines Optional. Specifies the maximum line width. Default is 75 Optional. Specifies the characters to use as break. Default is "\n" Optional. Specifies whether words longer than the specified width should be wrapped. Default is FALSE (nowrap)

Tips and Notes


Note: This function may leave white spaces at the beginning of a line.

Example 1
<?php $str = "An example on a long word is: Supercalifragulistic"; echo wordwrap($str,15); ?> The browser output of the code above will be: An example on a long word is: Supercalifragulistic If you select "View source" in the browser window, you will see the following HTML: <html> <body> An example on a long word is: Supercalifragulistic </body> </html>

Example 2
<?php $str = "An example on a long word is: Supercalifragulistic"; echo wordwrap($str,15,"<br />\n"); ?> The output of the code above will be: An example on a long word is: Supercalifragulistic

Example 3
<?php $str = "An example on a long word is: Supercalifragulistic"; echo wordwrap($str,15,"<br />\n",TRUE); ?> The output of the code above will be: An example on a long word is: Supercalifragul istic

Content Downloaded From www.w3schools.com

111

You might also like