Collection of php string functions

Source: Internet
Author: User
Tags crc32 shuffle

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. functions related to HTML code

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 -- encrypt an object using the MD5 Algorithm
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.