Collection of php string functions

Source: Internet
Author: User
Tags crc32 shuffle
Php string functions, which are commonly used in php. 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
.

Strip_tags ($ str [,'

']): 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 ,'

');


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"
"
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:

$ 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:

$ 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:

$ People = array ('name', 'sex', 'nation', 'birth ');
Foreach ($ people as $ mychrs)
Echo $ mychrs ."";
Sort ($ people );
Echo"
--- After sorting ---
";
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:

Echo "--- sort by numbers in ascending order ---
";
$ Num2 = array ('26', '3 ',);
Sort ($ num2, SORT_NUMERIC );
Foreach ($ num2 as $ mychrs)
Echo $ mychrs ."";

Echo"
--- Sort by character in ascending order ---
";
$ 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.

$ Doneles = array ('xm '=> 'name', 'xb' => 'sex', 'mz' => 'nation ', 'CS '=> 'birth ');
Foreach ($ minutes Les as $ mychrs)
Echo $ mychrs ."";

Echo"
-- Sort By element values in ascending order --
";
Asort ($ minutes les );
Foreach ($ minutes Les as $ mychrs)
Echo $ mychrs ."";

Echo"
-- Sort by keywords in ascending order --
";
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:

$ 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:

$ 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"
-- Reverse in the original order --
";
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.