25
1.The addcslashes() function returns a string with backslashes in front of the s pecified characters. addcslashes(string,characters) $str = addcslashes("Hello World!","W"); echo($str); Hello \World! 2. The addslashes() function returns a string with backslashes in front of prede fined characters. The predefined characters are: single quote (') double quote (") backslash (\) NULL addslashes(string) $str = addslashes('What does "yolo" mean?'); echo($str); What does \"yolo\" mean? 3.The chop() function removes whitespaces or other predefined characters from th e right end of a string chop(string,charlist) $str = "Hello World!"; echo $str . "<br>"; echo chop($str,"World!"); Hello World! Hello 4.The chr() function returns a character from the specified ASCII value. The ASCII value 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. chr(ascii) echo chr(52) . "<br>"; // Decimal value echo chr(052) . "<br>"; // Octal value echo chr(0x52) . "<br>"; // Hex value 4 * R 5. The chunk_split() function splits a string into a series of smaller parts. Note: This function does not alter the original string. chunk_split(string,length,end) $str = "Hello world!"; echo chunk_split($str,1,"."); H.e.l.l.o. .w.o.r.l.d.!. 6. The convert_cyr_string() function converts a string from one Cyrillic charact er-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 Note: This function is binary-safe.

PHP Srring Functions

Embed Size (px)

Citation preview

Page 1: PHP Srring Functions

1.The addcslashes() function returns a string with backslashes in front of the specified characters.addcslashes(string,characters)

$str = addcslashes("Hello World!","W");echo($str);

Hello \World!2. The addslashes() function returns a string with backslashes in front of predefined characters.The predefined characters are:single quote (')double quote (")backslash (\)NULLaddslashes(string)

$str = addslashes('What does "yolo" mean?');echo($str);

What does \"yolo\" mean?3.The chop() function removes whitespaces or other predefined characters from the right end of a stringchop(string,charlist)

$str = "Hello World!";echo $str . "<br>";echo chop($str,"World!");

Hello World!Hello 4.The chr() function returns a character from the specified ASCII value.The ASCII value 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.chr(ascii)

echo chr(52) . "<br>"; // Decimal valueecho chr(052) . "<br>"; // Octal valueecho chr(0x52) . "<br>"; // Hex value4*R5. The chunk_split() function splits a string into a series of smaller parts.Note: This function does not alter the original string.chunk_split(string,length,end)

$str = "Hello world!";echo chunk_split($str,1,".");H.e.l.l.o. .w.o.r.l.d.!.6. The convert_cyr_string() function converts a string from one Cyrillic character-set to another.The supported Cyrillic character-sets are:k - koi8-rw - windows-1251i - iso8859-5a - x-cp866d - x-cp866m - x-mac-cyrillicNote: This function is binary-safe.

Page 2: PHP Srring Functions

The convert_cyr_string() function converts a string from one Cyrillic character-set to another.The supported Cyrillic character-sets are:

k - koi8-rw - windows-1251i - iso8859-5a - x-cp866d - x-cp866m - x-mac-cyrillic

Note: This function is binary-safe.convert_cyr_string(string,from,to)

$str = "Hello world! æøå";echo $str . "<br>";echo convert_cyr_string($str,'w','a');

Hello world! æøåHello world! ¦è¥ In this example we convert a string from the character-set "w" (windows-1251) to "a" (x-cp866).7. The convert_uudecode() function decodes a uuencoded string.This function is often used together with the convert_uuencode() function.

convert_uudecode(string)

$str = ",2&5L;&\@=V]R;&0A `";echo convert_uudecode($str);

Hello world!8. The convert_uuencode() function encodes a string using the uuencode algorithm.

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.

convert_uuencode(string)

$str = "Hello world!";echo convert_uuencode($str);

,2&5L;&\@=V]R;&0A `9. The count_chars() function returns information about characters used in a string (for example, how many times an ASCII character occurs in a string, or which characters that have been used or not been used in a string). Syntax

count_chars(string,mode)

$str = "Hello World!";echo count_chars($str,3);

The parameter "mode 3" will return a string with all the different characters used. In this example, the characters used in "Hello World!" are:!HWdelor10. The crc32() function calculates a 32-bit CRC (cyclic redundancy checksum) fo

Page 3: PHP Srring Functions

r a string.

This function can be used to validate data integrity.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.Syntaxcrc32(string)

$str = crc32("Hello World!");printf("%u\n",$str);

47245635511. 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.

Syntaxcrypt(str,salt)

12. The explode() function breaks a string into an array.

Note: The "separator" parameter cannot be an empty string.Note: This function is binary-safe.Syntaxexplode(separator,string,limit)

$str = "Hello world. It's a beautiful day.";print_r (explode(" ",$str));

Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )13. 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.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 two.Tip: Related functions: printf(), sprintf(), vprintf(), vsprintf() and vfprintf()

Syntaxfprintf(stream,format,arg1,arg2,arg++)

$number = 9;$str = "Beijing";$file = fopen("test.txt","w");

Page 4: PHP Srring Functions

echo fprintf($file,"There are %u million bicycles in %s.",$number,$str); The output of the code above will be:40

The following text will be written to the file "test.txt":There are 9 million bicycles in Beijing.14. The get_html_translation_table() function returns the translation table used by the htmlentities() and htmlspecialchars() functions.

Tip: Some characters can be encoded several ways. The get_html_translation_table() function returns the most common encoding.Syntaxget_html_translation_table(function,flags,character-set)

print_r (get_html_translation_table()); // HTML_SPECIALCHARS is default.

Array ( ["] => " [&] => & [<] => < [>] => > )15. The html_entity_decode() function converts HTML entities to characters.The html_entity_decode() function is the opposite of htmlentities().Syntaxhtml_entity_decode(string,flags,character-set)

$str = "&lt;&copy; W3S&ccedil;h&deg;&deg;&brvbar;&sect;&gt;";echo html_entity_decode($str);?>The HTML output of the code above will be (View Source):<!DOCTYPE html><html><body><? W3S?h????></body></html> The browser output of the code above will be:<? W3S?h????>$str = "&lt;&copy; W3S&ccedil;h&deg;&deg;&brvbar;&sect;&gt;";echo html_entity_decode($str);?>The HTML output of the code above will be (View Source):<!DOCTYPE html><html><body><? W3S?h????></body></html> The browser output of the code above will be:<? W3S?h????>16. The htmlentities() function converts characters to HTML entities.Tip: To convert HTML entities back to characters, use the html_entity_decode() function.Tip: Use the get_html_translation_table() function to return the translation table used by htmlentities(). Syntaxhtmlentities(string,flags,character-set,double_encode)

$str = "<© W3Sçh°°¦§>";echo htmlentities($str);?>

Page 5: PHP Srring Functions

<p>Converting characters into entities are often used to prevent browsers from using it as an HTML element. This can be especially useful to prevent code from running when users have access to display input on your homepage.</p>Converting characters into entities are often used to prevent browsers from using it as an HTML element. This can be especially useful to prevent code from running when users have access to display input on your homepage.17. 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().

Syntaxhtmlspecialchars_decode(string,flags)

$str = "This is some &lt;b&gt;bold&lt;/b&gt; text.";echo htmlspecialchars_decode($str);?>The HTML output of the code above will be (View Source):<!DOCTYPE html><html><body>This is some <b>bold</b> text.</body></html>

The browser output of the code above will be:This is some bold text.18. 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;Tip: To convert special HTML entities back to characters, use the htmlspecialchars_decode() function.

Syntaxhtmlspecialchars(string,flags,character-set,double_encode)

$str = "This is some <b>bold</b> text.";echo htmlspecialchars($str);?>

<p>Converting < and > into entities are often used to prevent browsers from using it as an HTML element. This can be especially useful to prevent code from running when users have access to display input on your homepage.</p>

This is some <b>bold</b> text.

Page 6: PHP Srring Functions

Converting < and > into entities are often used to prevent browsers from using it as an HTML element. This can be especially useful to prevent code from running when users have access to display input on your homepage.19. The implode() function returns a string from the elements of an array.

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.Note: This function is binary-safe.Syntaximplode(separator,array)

$arr = array('Hello','World!','Beautiful','Day!');echo implode(" ",$arr);

Hello World! Beautiful Day!20. The join() function returns a string from the elements of an array.

The join() function is an alias of the implode() function.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.

Syntaxjoin(separator,array)

$arr = array('Hello','World!','Beautiful','Day!');echo join(" ",$arr);

Hello World! Beautiful Day!21. The lcfirst() function converts the first character of a string to lowercase.Related functions:ucfirst() - converts the first character of a string to uppercaseucwords() - converts the first character of each word in a string to uppercasestrtoupper() - converts a string to uppercasestrtolower() - converts a string to lowercase

Syntaxlcfirst(string)

echo lcfirst("Hello world!");hello world!22. 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.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 modification

Page 7: PHP Srring Functions

s needed.

Syntaxlevenshtein(string1,string2,insert,replace,delete)

echo levenshtein("Hello World","ello World");echo "<br>";echo levenshtein("Hello World","ello World",10,20,30);13023. 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 symbol1 - The + sign is placed in front of the quantity and currency symbol2 - The + sign is placed after the quantity and currency symbol3 - The + sign is placed immediately in front of the currency symbol4 - The + sign is placed immediately after the currency symbol[n_sign_posn] - Formatting options:0 - Parentheses surround the quantity and currency symbol1 - The - sign is placed in front of the quantity and currency symbol2 - The - sign is placed after the quantity and currency symbol3 - The - sign is placed immediately in front of the currency symbol4 - 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)Tip: To define locale settings, see the setlocale() function.Tip: To view all available language codes, go to our Language code reference.

Syntaxlocaleconv()

setlocale(LC_ALL,"US");$locale_info = localeconv();print_r($locale_info);

Array ( [decimal_point] => . [thousands_sep] => , [int_curr_symbol] => USD [currency_symbol] => $ [mon_decimal_point] => . [mon_thousands_sep] => , [positive_si

Page 8: PHP Srring Functions

gn] => [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 ) )

24. The ltrim() function removes whitespace or other predefined characters from the left side of a string.Related functions: rtrim() - Removes whitespace or other predefined characters from the right side of a stringtrim() - Removes whitespace or other predefined characters from both sides of a string

Syntaxltrim(string,charlist)

$str = "Hello World!";echo $str . "<br>";echo ltrim($str,"Hello");

Hello World!World!25. 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."

To calculate the MD5 hash of a file, use the md5_file() function.Syntaxmd5(string,raw)

$str = "Hello";echo md5($str);

8b1a9953c4611296a827abf8c47804d726. 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."To calculate the MD5 hash of a string, use the md5() function.

Syntaxmd5_file(file,raw)

$filename = "test.txt";$md5file = md5_file($filename);echo $md5file;

Page 9: PHP Srring Functions

The output of the code above will be:d41d8cd98f00b204e9800998ecf8427e 27. 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.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.

Syntaxmetaphone(string,length)

echo metaphone("World");

WRLT28. 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.Note: The money_format() function does not work on Windows platforms.Tip: This function is often used together with the setlocale() function.Tip: To view all available language codes, go to our Language code reference.

Syntaxmoney_format(string,number)

$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 29. The nl_langinfo() function returns specific local information.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.

Syntaxnl_langinfo(element)

30. The nl2br() function inserts HTML line breaks (<br> or <br />) in front of each newline (\n) in a string.Syntaxnl2br(string,xhtml)

echo nl2br("One line.\nAnother line.");

One line.Another line.31. The number_format() function formats a number with grouped thousands.Note: This function supports one, two, or four parameters (not three).Syntaxnumber_format(number,decimals,decimalpoint,separator)

echo number_format("1000000")."<br>";echo number_format("1000000",2)."<br>";echo number_format("1000000",2,",",".");

Page 10: PHP Srring Functions

1,000,0001,000,000.001.000.000,0032. The ord() function returns the ASCII value of the first character of a string.Syntaxord(string)

echo ord("h")."<br>";echo ord("hello")."<br>";

10410433. The parse_str() function parses a query string into variables.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().Syntaxparse_str(string,array)

parse_str("name=Peter&age=43");echo $name."<br>";echo $age;

Peter4334. 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.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 two.Tip: Related functions: sprintf(), vprintf(), vsprintf(), fprintf() and vfprintf()

Syntaxprintf(format,arg1,arg2,arg++)

$number = 9;$str = "Beijing";printf("There are %u million bicycles in %s.",$number,$str);

There are 9 million bicycles in Beijing.35. The quoted_printable_decode() function decodes a quoted-printable string to an 8-bit ASCII string.

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.

Syntaxquoted_printable_decode(string)

$str = "Hello=0Aworld.";

Page 11: PHP Srring Functions

echo quoted_printable_decode($str);

Hello world.36. The quoted_printable_encode() function converts an 8-bit string to a quoted-printable string.

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.

Syntaxquoted_printable_encode(string) 37. The quoted_printable_encode() function converts an 8-bit string to a quoted-printable string.

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.Syntaxquoted_printable_encode(string)

$str = "Hello world. (can you hear me?)";echo quotemeta($str);

Hello world\. \(can you hear me\?\)38. The rtrim() function removes whitespace or other predefined characters from the right side of a string.Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a stringtrim() - Removes whitespace or other predefined characters from both sides of a stringSyntaxrtrim(string,charlist)

$str = "Hello World!";echo $str . "<br>";echo rtrim($str,"World!");

Hello World!Hello39. The setlocale() function sets locale information.

Locale information is language, monetary, time and other information specific for a geographical area.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)Tip: To get numeric formatting information, see the localeconv() function.

Syntaxsetlocale(constant,location)

echo setlocale(LC_ALL,"US");echo "<br>";echo setlocale(LC_ALL,NULL);

English_United States.1252English_United States.1252

Page 12: PHP Srring Functions

40. 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."Tip: To calculate the SHA-1 hash of a file, use the sha1_file() function.Syntaxsha1(string,raw)

$str = "Hello";echo sha1($str);f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf041. 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.

Syntaxsha1_file(file,raw)

$filename = "test.txt";$sha1file = sha1_file($filename);echo $sha1file;?>The output of the code above will be:aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d 42. The similar_text() function calculates the similarity between two strings.It can also calculate the similarity of the two strings in percent.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.Syntaxsimilar_text(string1,string2,percent)

echo similar_text("Hello World","Hello Peter");

743. 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.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.

Syntaxsoundex(string)

Page 13: PHP Srring Functions

$str = "Hello";echo soundex($str);

H40044. 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.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 two.Tip: Related functions: printf(), vprintf(), vsprintf(), fprintf() and vfprintf()

Syntaxsprintf(format,arg1,arg2,arg++)

$number = 9;$str = "Beijing";$txt = sprintf("There are %u million bicycles in %s.",$number,$str);echo $txt;

There are 9 million bicycles in Beijing.45. 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.Related functions:printf() - outputs a formatted stringsprintf() - writes a formatted string to a variableSyntaxsscanf(string,format,arg1,arg2,arg++)

$str = "age:30 weight:60kg";sscanf($str,"age:%d weight:%dkg",$age,$weight);// show types and valuesvar_dump($age,$weight);

int(30) int(60)

45. The str_getcsv() function parses a string for fields in CSV format and returns an array containing the fields read.

Syntaxstr_getcsv(string,separator,enclosure,escape) 46. The str_ireplace() function replaces some characters with some other characters in a string.

This function works by the following rules:If the string to be searched is an array, it returns an arrayIf the string to be searched is an array, find and replace is performed with every array elementIf both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replace

Page 14: PHP Srring Functions

If find is an array and replace is a string, the replace string will be used for every find valueNote: This function is case-insensitive. Use the str_replace() function to perform a case-sensitive search.Note: This function is binary-safe.

Syntaxstr_ireplace(find,replace,string,count)

echo str_ireplace("WORLD","Peter","Hello world!");

<p>In this example, we search for the string "Hello World!", find the value "WORLD" and then replace the value with "Peter".</p>Hello Peter! In this example, we search for the string "Hello World!", find the value "WORLD" and then replace the value with "Peter".47. The str_pad() function pads a string to a new length.

Syntaxstr_pad(string,length,pad_string,pad_type)

$str = "Hello World";echo str_pad($str,20,".");

Hello World.........

48. Definition and UsageThe str_repeat() function repeats a string a specified number of times.

Syntaxstr_repeat(string,repeat)

echo str_repeat(".",13);.............49. The str_replace() function replaces some characters with some other characters in a string.

This function works by the following rules:If the string to be searched is an array, it returns an arrayIf the string to be searched is an array, find and replace is performed with every array elementIf both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replaceIf find is an array and replace is a string, the replace string will be used for every find valueNote: This function is case-sensitive. Use the str_ireplace() function to perform a case-insensitive search.Note: This function is binary-safe.

Syntaxstr_replace(find,replace,string,count)

echo str_replace("world","Peter","Hello world!");

<p>In this example, we search for the string "Hello World!", find the value "world" and then replace the value with "Peter".</p>Hello Peter! In this example, we search for the string "Hello World!", find the value "world"

Page 15: PHP Srring Functions

and then replace the value with "Peter".50. 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.Tip: Encoding and decoding are done by the same function. If you pass an encoded string as argument, the original string will be returned.Syntaxstr_rot13(string)

echo str_rot13("Hello World");echo "<br>";echo str_rot13("Uryyb Jbeyq");Uryyb JbeyqHello World51. The str_shuffle() function randomly shuffles all the characters of a string.Syntaxstr_shuffle(string)

echo str_shuffle("Hello World");?>

<p>Try to refresh the page. This function will randomly shuffle all characters each time.</p>echo str_shuffle("Hello World");?>

<p>Try to refresh the page. This function will randomly shuffle all characters each time.</p>52. The str_split() function splits a string into an array.

Syntaxstr_split(string,length)

print_r(str_split("Hello"));

Array ( [0] => H [1] => e [2] => l [3] => l [4] => o )

53. The str_word_count() function counts the number of words in a string.

Syntaxstr_word_count(string,return,char)

echo str_word_count("Hello world!");254. The strcasecmp() function compares two strings.

Tip: The strcasecmp() function is binary-safe and case-insensitive.Tip: This function is similar to the strncasecmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncasecmp().

Syntaxstrcasecmp(string1,string2)

echo strcasecmp("Hello world!","HELLO WORLD!");0 If this function returns 0, the two strings are equal.55. The strchr() function searches for the first occurrence of a string inside another string.

Page 16: PHP Srring Functions

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

Syntaxstrchr(string,search,before_search);

echo strchr("Hello world!","world");

world!56. The strcmp() function compares two strings.

Note: The strcmp() function is binary-safe and case-sensitive.Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp().

Syntaxstrcmp(string1,string2)

echo strcmp("Hello world!","Hello world!");

0 If this function returns 0, the two strings are equal.57. The strcoll() function compares two strings.

The comparison of the strings may vary depending on the locale settings (A<a or A>a).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().

Syntaxstrcoll(string1,string2)

setlocale (LC_COLLATE, 'NL');echo strcoll("Hello World!","Hello World!");echo "<br>";

setlocale (LC_COLLATE, 'en_US');echo strcoll("Hello World!","Hello World!");?>

<p>If this function returns 0, the two strings are equal.</p>00 If this function returns 0, the two strings are equal.58. The strcspn() function returns the number of characters (including whitespaces) found in a string before any part of the specified characters are found.

Tip: Use the strspn() function to the number of characters found in the string that contains only characters from a specified character list.Note: This function is binary-safe.

Syntaxstrcspn(string,char,start,length)

echo strcspn("Hello world!","w");

Page 17: PHP Srring Functions

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

Note: HTML comments are always stripped. This cannot be changed with the allow parameter.Note: This function is binary-safe.

Syntaxstrip_tags(string,allow)

echo strip_tags("Hello <b>world!</b>");?>

<p>This function strips a string from HTML, XML, and PHP tags. In this example, the <b> tag gets stripped.</p>Hello world! This function strips a string from HTML, XML, and PHP tags. In this example, the <b> tag gets stripped.60. The stripcslashes() function removes backslashes added by the addcslashes() function.

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

Syntaxstripcslashes(string)

echo stripslashes("Hello \World!");

Hello World!61. The stripslashes() function removes backslashes added by the addslashes() function.

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

Syntaxstripslashes(string)

echo stripslashes("Who\'s Peter Griffin?");

Who's Peter Griffin?62. The stripos() function finds the position of the first occurrence of a string inside another string.

Note: The stripos() function is case-insensitive.Note: This function is binary-safe.Related functions:

strripos() - Finds the position of the last occurrence of a string inside another string (case-insensitive)strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)strrpos() - Finds the position of the last occurrence of a string inside another string (case-sensitive)

Syntaxstripos(string,find,start)

Page 18: PHP Srring Functions

echo stripos("I love php, I love php too!","PHP");

763. The stristr() function searches for the first occurrence of a string inside another string.

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

Syntaxstristr(string,search,before_search)

echo stristr("Hello world!","WORLD");

world!64. The strlen() function returns the length of a string.

Syntaxstrlen(string)

echo strlen("Hello");565. 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.Note: The strnatcasecmp() is case-insensitive.

Syntaxstrnatcasecmp(string1,string2)

echo strnatcasecmp("2Hello world!","10Hello WORLD!");echo "<br>";echo strnatcasecmp("10Hello world!","2Hello WORLD!");

-1166. 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.Note: This function is case-sensitive.

Syntaxstrnatcmp(string1,string2)

echo strnatcmp("2Hello world!","10Hello world!");echo "<br>";echo strnatcmp("10Hello world!","2Hello world!");

-1167. The strncasecmp() function compares two strings.

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

Page 19: PHP Srring Functions

Tip: This function is similar to the strcasecmp() function, except that strcasecmp() does not have the length parameter.

Syntaxstrncasecmp(string1,string2,length)

echo strncasecmp("Hello world!","hello earth!",6);

068. The strncmp() function compares two strings.

Note: The strncmp() is binary-safe and case-sensitive.Tip: This function is similar to the strcmp() function, except that strcmp() does not have the length parameter.

Syntaxstrncmp(string1,string2,length)

echo strncmp("Hello world!","Hello earth!",6);069. The strpbrk() function searches a string for any of the specified characters.

Note: This function is case-sensitive.This function returns the rest of the string from where it found the first occurrence of a specified character, otherwise it returns FALSE.

Syntaxstrpbrk(string,charlist)

echo strpbrk("Hello world!","oe"); ?>

<p>"e" is the first occurrence of the specified characters. This function will therefore output "ello world!", because it returns the rest of the string from where it found the first occurrence of "e".</p>ello world! "e" is the first occurrence of the specified characters. This function will therefore output "ello world!", because it returns the rest of the string from where it found the first occurrence of "e".70. The strpos() function finds the position of the first occurrence of a string inside another string.

Note: The strpos() function is case-sensitive.Note: This function is binary-safe.Related functions:strrpos() - Finds the position of the last occurrence of a string inside another string (case-sensitive)stripos() - Finds the position of the first occurrence of a string inside another string (case-insensitive)strripos() - Finds the position of the last occurrence of a string inside another string (case-insensitive)

Syntaxstrpos(string,find,start)

echo strpos("I love php, I love php too!","php");

7

Page 20: PHP Srring Functions

71. 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.

Note: This function is binary-safe.

Syntaxstrrchr(string,char)

echo strrchr("Hello world!","world");

world!

72. The strrev() function reverses a string.Syntaxstrrev(string)

echo strrev("Hello World!");

!dlroW olleH73. The strripos() function finds the position of the last occurrence of a string inside another string.

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

Related functions:stripos() - Finds the position of the first occurrence of a string inside another string (case-insensitive)strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)strrpos() - Finds the position of the last occurrence of a string inside another string (case-sensitive)

Syntaxstrripos(string,find,start)

echo strripos("I love php, I love php too!","PHP");

1974. The strrpos() function finds the position of the last occurrence of a string inside another string.

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

Related functions:strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)stripos() - Finds the position of the first occurrence of a string inside another string (case-insensitive)strripos() - Finds the position of the last occurrence of a string inside another string (case-insensitive)

Syntaxstrrpos(string,find,start)

echo strrpos("I love php, I love php too!","php");

19

Page 21: PHP Srring Functions

75. The strspn() function returns the number of characters found in the string that contains only characters from the charlist parameter.

Tip: Use the strcspn() function to return the number of characters found in a string before any part of the specified characters are found.Note: This function is binary-safe.

Syntax

strspn(string,charlist,start,length)

echo strspn("Hello world!","kHlleo");

576. The strstr() function searches for the first occurrence of a string inside another string.Note: This function is binary-safe.Note: This function is case-sensitive. For a case-insensitive search, use stristr() function.

Syntaxstrstr(string,search,before_search)

echo strstr("Hello world!","world");world!77. The strrev() function reverses a string.

Syntaxstrrev(string)

echo strrev("Hello World!");

!dlroW olleH78. The strripos() function finds the position of the last occurrence of a string inside another string.

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

Related functions:stripos() - Finds the position of the first occurrence of a string inside another string (case-insensitive)strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)strrpos() - Finds the position of the last occurrence of a string inside another string (case-sensitive)

Syntaxstrripos(string,find,start)

echo strripos("I love php, I love php too!","PHP");

19

79. The strrpos() function finds the position of the last occurrence of a string inside another string.Note: The strrpos() function is case-sensitive.Related functions:strpos() - Finds the position of the first occurrence of a string inside another

Page 22: PHP Srring Functions

string (case-sensitive)stripos() - Finds the position of the first occurrence of a string inside another string (case-insensitive)strripos() - Finds the position of the last occurrence of a string inside another string (case-insensitive)

Syntaxstrrpos(string,find,start)

echo strrpos("I love php, I love php too!","php");

1980. The strspn() function returns the number of characters found in the string that contains only characters from the charlist parameter.

Tip: Use the strcspn() function to return the number of characters found in a string before any part of the specified characters are found.Note: This function is binary-safe.

Syntaxstrspn(string,charlist,start,length)

echo strspn("Hello world!","kHlleo");581. The strstr() function searches for the first occurrence of a string inside another string.

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

Syntaxstrstr(string,search,before_search)

echo strstr("Hello world!","world");

world!82. The substr() function returns a part of a string.

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

Syntaxsubstr(string,start,length)

echo substr("Hello world",6);

world83. The substr_compare() function compares two strings from a specified start position.

Tip: This function is binary-safe and optionally case-sensitive.Syntaxsubstr_compare(string1,string2,startpos,length,case)

echo substr_compare("Hello world","Hello world",0);

<p>If this function returns 0, the two strings are equal.</p>0

Page 23: PHP Srring Functions

If this function returns 0, the two strings are equal.84. The substr_count() function counts the number of times a substring occurs in a string.

Note: The substring is case-sensitive.Note: This function does not count overlapped substrings (see example 2).Note: This function generates a warning if the start parameter plus the length parameter is greater than the string length (see example 3).

Syntaxsubstr_count(string,substring,start,length)

echo substr_count("Hello world. The world is nice","world");285. The substr_replace() function replaces a part of a string with another string.

Note: If the start parameter is a negative number and length is less than or equal to start, length becomes 0.Note: This function is binary-safe.

Syntaxsubstr_replace(string,replacement,start,length)

echo substr_replace("Hello","world",0); // 0 will start replacing at the first character in the string

world86. The trim() function removes whitespace and other predefined characters from both sides of a string.Related functions:

ltrim() - Removes whitespace or other predefined characters from the left side of a stringrtrim() - Removes whitespace or other predefined characters from the right side of a string

Syntaxtrim(string,charlist)

$str = "Hello World!";echo $str . "<br>";echo trim($str,"Hed!");

Hello World!llo Worl87. The ucfirst() function converts the first character of a string to uppercase.

Related functions:lcfirst() - converts the first character of a string to lowercaseucwords() - converts the first character of each word in a string to uppercasestrtoupper() - converts a string to uppercasestrtolower() - converts a string to lowercase

Syntaxucfirst(string)

echo ucfirst("hello world!");

Page 24: PHP Srring Functions

Hello world!88. The ucwords() function converts the first character of each word in a string to uppercase.

Note: This function is binary-safe.Related functions:ucfirst() - converts the first character of a string to uppercaselcfirst() - converts the first character of a string to lowercasestrtoupper() - converts a string to uppercasestrtolower() - converts a string to lowercase

Syntaxucwords(string)

echo ucwords("hello world");

Hello World89. 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.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 two.Tip: Related functions: fprintf(), printf(), sprintf(), vprintf() and vsprintf().

Syntaxvfprintf(stream,format,argarray)

$number = 9;$str = "Beijing";$file = fopen("test.txt","w");echo vfprintf($file,"There are %u million bicycles in %s.",array($number,$str));?>The output of the code above will be:40 The following text will be written to the file "test.txt":There are 9 million bicycles in Beijing.

90. 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.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 two.

Tip: Related functions: sprintf(), printf(), vsprintf(), fprintf() and vfprintf()Syntax

vprintf(format,argarray)

Page 25: PHP Srring Functions

$number = 9;$str = "Beijing";

vprintf("There are %u million bicycles in %s.",array($number,$str));There are 9 million bicycles in Beijing.91. 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.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 two.Tip: Related functions: fprintf(), vfprintf(), printf(), sprintf() and vprintf().

Syntaxvsprintf(format,argarray)

$number = 9;$str = "Beijing";$txt = vsprintf("There are %u million bicycles in %s.",array($number,$str));echo $txt;

There are 9 million bicycles in Beijing.

92.The wordwrap() function wraps a string into new lines when it reaches a specific length.

Note: This function may leave white spaces at the beginning of a line.Syntaxwordwrap(string,width,break,cut)

$str = "An example of a long word is: Supercalifragulistic";echo wordwrap($str,15,"<br>\n");

An example of along word is:SupercalifragulisticThe end