Collection of PHP string functions

Source: Internet
Author: User
Tags crc32 rtrim

1. character location search function:
Strpos ($ STR, search, [int]): searches for the first position of search in $ STR starting from int;
Stripos ($ STR, search, [int]): the position where the string first appears in another string. This function is case insensitive.
Strrpos ($ STR, search, [int]): searches for the last position of search in $ STR from int

2. Extract sub-character functions (dual-byte)
Submit ($ STR, int start [, int length]): Extracts [length strings] starting from the Strat position in $ Str.
Strstr ($ str1, $ str2): searches for $ str2 from $ str1 (the first position) and truncates the string from the start to the end. If not, false is returned.
Stristr () is the same as strstr, but is case insensitive.
Strrchr () is returned from the last searched character. Usage: get the file name in the path

3. Replace string
Str_replace (search, replace, $ Str): Search for search from $ STR and replace it with replace.

Str_irreplace (search, replace, $ Str ):

Strtr ($ STR, search, replace): In this function, replace cannot be "";

Substr_replace ($ STR, $ rep, $ start [, length]) $ STR original string, $ new after rep replacement

String, starting position of $ start, and length of $ length. Optional.

4. Character Length
Int strlen ($ Str)

5. Comparison of character Functions
Int strcmp ($ str1, $ str2): $ str1 >=< $ str2 is positive 1, 0,-1 (string comparison)
Strcasecmp () Same as above (case-insensitive)

Strnatcmp ("4", "14") compares strings in natural order
Strnatcasecmp () is the same as above (case sensitive)

6. Split into array Functions
Str_split ($ STR, Len): splits $ STR by LEN Length and returns an array.
Split (search, $ STR [, int]): splits $ STR by the search character and returns the number of times the array int is split.
Expload (search, $ STR [, int])

7. Remove spaces: ltrim, rtrim, and trim

8. Space Function
Chunk_split ($ STR, 2); add a space to the $ STR string containing 2 characters;

9. CHR and ord -- return the specified character or ASCII

10. htmlCodeRelated functions

Nl2br (): converts \ n to <br>.

Strip_tags ($ STR [, '<p>']): removes HTML and PHP tags.
In $ STR, all HTML and PHP code will be removed. The optional parameters are HTML and PHP code.

Code written by optional parameters.
For example, Echo strip_tags ($ text, '<br> <p> ');

Htmlspecialchars ($ STR [, parameter]): the HTML code parameters output normally on the page are converted.

11. case-insensitive conversion functions
Strtolower ($ Str) string to lowercase
Strtoupper ($ Str) string to uppercase
Ucfirst ($ Str) converts the first character of the function to uppercase.
Ucwords ($ Str) converts the first letter of each word to uppercase

12. Database-related functions
Addslashes ($ Str): enables single quotation marks ('), double quotation marks ("), backslash (\), and NUL in Str.

String \',\",\\.
Magic_quotes_gpc = on automatically escapes the get post cookie content

Get_magic_quotes_gpc () Check whether magic_quotes_gpc is enabled

Stripslashes () removes the backslash from the string

13. Connection Functions
Implode (STR, $ ARR) concatenates a string array into a string based on specified characters. The implode () function has an alias function for join.

Addcslashes -- add backslash escape characters to some characters in the string
Addslashes -- escape characters in a string in a specified way
Bin2hex -- convert binary data to hexadecimal Representation
Chr -- returns the ASCII code of a character.
Chunk_split -- Splits a string into small parts based on a certain character Length
Convert_cyr_string -- converts a Slavic character to another character.
Convert_uudecode -- decrypts a string
Convert_uuencode -- encrypt a string
Count_chars -- returns the character usage information in a string.
CRC32 -- calculate the CRC32 polynomial of a string
Crypt -- one-way hash encryption function
Explode -- convert a string into an array using a delimiter
Fprintf -- return data as required and directly write data to the Document Stream
Get_html_translation_table -- returns the HTML entity that can be converted.
Html_entity_decode -- the inverse function of the htmlentities () function, which converts an HTML object to a character
Htmlentities -- convert some characters in a string into HTML entities
Htmlspecialchars_decode -- the inverse function of the htmlspecialchars () function, which converts HTML objects to characters.
Htmlspecialchars -- converts some characters in a string to HTML entities
Implode -- convert an array into a string using a specific delimiter
Join -- convert an array into a string, alias of the implode () function
Levenshtein -- calculate the difference between two words
Localeconv -- get format definitions related to numbers
Ltrim -- removes white spaces or specified characters on the left of the string
Md5_file -- perform MD5 for an object Algorithm Encryption
MD5-encrypt a string using the MD5 Algorithm
Metaphone -- determines the pronunciation rules of a string
Money_format -- format the output of numbers based on parameters
Nl_langinfo -- Query Language and local information
Nl2br -- replace the linefeed "\ n" in the string with "<br/>"
Number_format -- format the output of numbers based on parameters
Ord: converts an ascii code to a character.
Parse_str -- convert a string of a certain format to a variable and a value
Print -- used to output a separate value
Printf -- display data as required
Quoted_printable_decode -- encrypt a string into an 8-bit binary string
Quotemeta -- escape several specific characters
Rtrim -- remove the white space or specified characters on the right of the string
Setlocale -- set the local format of numbers, dates, and so on
Sha1_file -- encrypt a file using the sha1 Algorithm
Sha1 -- encrypt a string using the sha1 Algorithm
Similar_text -- compares two strings and returns the number of similar characters that the system considers.
Soundex-rules for determining the pronunciation of a string
Sprintf -- return data as required, but no output
Sscanf -- you can format strings.
Str_ireplace -- matches and replaces strings like the str_replace () function, but is case insensitive.
Str_pad -- pad both sides of the string
Str_repeat -- repeat the string
Str_replace -- match and replace strings
Str_rot13 -- encrypt the string with rot13
Str_shuffle -- random sorting of characters in a string
Str_split -- Splits a string into an Array Based on the Character Spacing
Str_word_count -- get the English word information in the string
Strcasecmp -- compare the string size, case insensitive
Strchr -- returns the alias of some strstr () functions of a string through comparison.
Strcmp -- compare the size of a string
Strcoll-compare the string Size Based on Local Settings
Strcspn -- returns the value of consecutive non-matching lengths.
Strip_tags -- remove the HTML and PHP code in a string
Stripcslashes -- returns the string processed by the addcslashes () function escape function.
Stripos -- locate and return the position of the first matching item. The matching is case insensitive.
Stripslashes -- returns the string that has been escaped by the implicit addslashes () function.
Stristr -- returns the part of a string through comparison. The comparison is case insensitive.
Strlen -- get the encoding length of a string
Strnatcasecmp -- use the natural sorting method to compare the string size, case insensitive
Strnatcmp -- use the natural sorting method to compare the string size
Strncasecmp-compare the size of the First n characters of a string, case insensitive
Strncmp -- compare the size of the First n characters of a string
Strpbrk -- returns the part of a string through comparison
Strpos -- locate and return the position of the first matching item
Strrchr -- returns the part of a string through comparison from the back to the back
Strrev -- reverse arrange all letters in the string
Strripos -- search from the back and return the position of the first matching item. The matching is case insensitive.
Strrpos -- search from the back and return the position of the first matching item
Strspns -- value that matches and returns the consecutive length of a character
Strstr -- returns the part of a string through comparison
Strtok -- use a specified number of characters to separate strings
Strtolower -- convert string to lowercase
Strtoupper -- converts a string to uppercase
Strtr -- replace string comparison
Substr_compare -- Comparison after string Truncation
Substr_count -- calculates the number of occurrences of a character segment in a string.
Substr_replace -- replace some characters in the string
Substr -- truncates a string
Trim -- removes spaces or specified characters on both sides of the string
Ucfirst -- converts the first letter of the given string into uppercase letters.
Ucwords -- converts the first letter of each English word of the given string into uppercase letters.
Vfprintf -- return data as required and directly write data to the Document Stream
Vprintf -- display data as required
Vsprintf -- return data as required, but no output
Wordwrap-Splits a string based on a certain character Length

1. quickly create an array function range ()

For example, the range () function can quickly create a number array from 1 to 9:

<? PHP
$ Numbers = range (); // use range to directly create 1 ~ 9. An array composed of 9 numbers. It ends with "1" and "9.
Echo $ numbers [1]; // output the second array value created: 2; echo $ numbers [0]; then enter the first value: 0.
?>

Of course, range (9, 1) is used to create a number array from 9 to 1. At the same time, range () can also create a character array from A to Z:

<? PHP
$ Numbers = range (A, Z );
Foreach ($ numbers as $ mychrs) // traverses the $ numbers array. The current unit value in each loop is assigned to $ mychrs.
Echo $ mychrs. ""; // output a B c d e f g h I j k l m n o p q r s t u v w x Y Z
?>

// Foreach is a simple way to traverse arrays. foreach can only be used for arrays. If you try to use it for another data type or an uninitialized variable, an error will occur, it has two formats:

Foreach (array_expression as $ value) statementforeach (array_expression as $ key => $ value) Statement
The first format traverses the given array_expression array. In each loop, the value of the current unit is assigned to $ value and the pointer inside the array moves forward (so the next unit will be obtained in the next loop ). In the second format, only the key names of the current Unit are assigned to the variable $ key in each loop.

Note the case sensitivity when using character arrays. For example, range (A, Z) and range (A, Z) are different.

The range () function also has a third parameter, which is used to set the step size. For example, the array elements created by range (, 3) are: 1, 4, and 7.

2. Sorting regular arrays in PHP

Generally, all elements in an array are represented by characters or numbers. Therefore, you can sort the array elements in ascending order. This function is sort (). For example:

<? PHP
$ People = array ('name', 'sex', 'nation', 'birth ');
Foreach ($ people as $ mychrs)
Echo $ mychrs ."";
Sort ($ people );
Echo "<br/> --- sorted --- <br/> ";
Foreach ($ people as $ mychrs)
Echo $ mychrs ."";
?>

The array elements in ascending order are displayed as birth name Nation sex. Of course, the sort () function is case-sensitive (the order of letters from large to small is:... Z... A... Z)

The sort () function also has a second parameter. The ascending rule is used to compare numbers and strings. For example:

<? PHP
Echo "--- sort by numbers in ascending order --- <br/> ";
$ Num2 = array ('26', '3 ',);
Sort ($ num2, sort_numeric );
Foreach ($ num2 as $ mychrs)
Echo $ mychrs ."";

Echo "<br/> --- sort by character in ascending order --- <br/> ";
$ Num3 = array ('26', '3 ');
Sort ($ num3, sort_string );
Foreach ($ num3 as $ mychrs)
Echo $ mychrs ."";
?>

Sort_numeric and sort_string are used to declare the ascending order of numbers or characters. If the numbers are listed in ascending order: 3, 26, but if the characters are listed in ascending order, they are listed as 26, 3.

In PHP, in addition to the ascending function, there are also descending or reverse sort functions, which are rsort () functions, such:

$ Num1 = range (1, 9 );
Rsort ($ num1); // here it is actually equivalent to range (9, 1)

3. Sorting of associated arrays in PHP

In addition to numeric index arrays, PHP also supports related arrays. For example, the following array is a correlated array:

$ Doneles = array ('xm '=> 'name', 'xb' => 'sex', 'mz' => 'nation ', 'cs '=> 'birth ');

By default, sort ($ sort les) is used to sort the values defined by elements in ascending order. In an associated array, the asort () function can be used to sort the values in ascending order, in the joined array, the most important thing is to sort by keywords (such as XM, XB, Mz, etc.) in ascending order. This method uses the ksort () function.

<? PHP
$ Doneles = array ('xm '=> 'name', 'xb' => 'sex', 'mz' => 'nation ', 'cs '=> 'birth ');
Foreach ($ minutes les as $ mychrs)
Echo $ mychrs ."";

Echo "<br/> -- sort by element values in ascending order -- <br/> ";
Asort ($ minutes les );
Foreach ($ minutes les as $ mychrs)
Echo $ mychrs ."";

Echo "<br/> -- sort by keywords in ascending order -- <br/> ";
Ksort ($ cmdles );
Foreach ($ minutes les as $ mychrs)
Echo $ mychrs ."";
?>
Corresponds to the reverse sort rsort () descending function of the sort () ascending function of a conventional array, and the associated array also has the corresponding descending function: asort () functions: arsort (), ksort (), and krsort.
Memory: The prototype function is sort (), where A and K indicate that the correlated array must be prefixed, and R is used for reverse sorting.

4. random sorting of PHP array elements

In PHP, the shuffle () function is used to randomly sort array elements. Different sorting combinations are displayed each time, for example:

<? PHP
$ Fer = array ('cnbruce ', 'cnrose', 'cnjames ', 'cnanne ');
Shuffle ($ FER); // sort immediately. A random sorting is performed every time the page is refreshed.

Foreach ($ FER as $ mychrs)
Echo $ mychrs ."";
?>

5. php array in reverse order

In PHP, The array_reverse () function can be used to sort array elements in reverse order. For example:

<? PHP
$ Fer = array ('cnbruce ', 'cnrose', 'cnjames ', 'cnanne ');
Foreach ($ FER as $ mychrs)
Echo $ mychrs ."";

$ Fer = array_reverse ($ FER); // sorts the elements in the array in reverse order according to the original order.
Echo "<br/> -- reverse in the original order -- <br/> ";
Foreach ($ FER as $ mychrs)
Echo $ mychrs ."";
?>

Output: cnbruce cnrose cnjames cnanne
-- Reverse in the original order --
Cnanne cnjames cnrose cnbruce

Note that $ fer = array_reverse ($ FER) here; Any sorting function before this is only declared reference, and the original array is not redefined, however, when I debug this function, I need to redefine it. This is because array_reverse () is the modified copy of the original array. If you do not need the original array, You can redefine it to overwrite the original array. Otherwise, you can define an array to save the copy, for example: $ fer_bak = array_reverse ($ fer_bak );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.