PHP String function Collection _php tips

Source: Internet
Author: User
Tags chr crc32 lowercase ord rtrim shuffle strcmp strlen
1 Find character position function:
Strpos ($str, Search,[int]): Find the first position of search in $str starting from int;
Stripos ($str, search,[int]): function returns the position where the string first appears in another string. This function is not sensitive to case
Strrpos ($str, Search,[int]): Find the last occurrence of search in $str from int

2. Extract the character function (double byte)
Submit ($str, int start[,int length]): Extracts [length string] from strat position in $str.
Strstr ($str 1, $str 2): Searches the $str2 from the $STR1 (the first position) and intercepts it to the ending string, or false if not.
The STRISTR () feature is the same as STRSTR, but is case-insensitive.
STRRCHR () return from the last search to the word entered prompt; use: take the filename in the path

3. Replacement string
Str_replace (Search,replace, $STR): Search from $STR Replace with replace

Str_irreplace (Search,replace, $STR):

STRTR ($str, search,replace): Replace cannot be "" in this function;

Substr_replace ($Str, $rep, $start [, length]) $str The original string, $rep replaced by the new

The string, $start the starting position, $length the length of the replacement, which is optional

4, character length
int strlen ($STR)

5. Comparing character functions
int strcmp ($str 1, $str 2): $str 1>=< $str 2 is positive 1,0,-1 (string comparison)
STRCASECMP () ditto (case-insensitive)

STRNATCMP ("4", "14") compare strings by natural sort
STRNATCASECMP () ditto, (case-sensitive)

6. Split the group function
Str_split ($str, Len): Dividing the $str by Len length to return an array
Split (search, $str [, int]): Split $str by search character return array int is split several times, the following will not be split
Expload (Search, $str [, int])

7, remove space: LTrim, RTrim, Trim

8, add space function
Chunk_split ($STR, 2); Add a space to the $STR character by 2 characters;

9, CHR, ord--returns the specified character or ASCII

10, HTML code related functions

NL2BR (): Convert \ n to <br>.

Strip_tags ($str [, ' <p> ']): Removing HTML and PHP tags
All HTML and PHP code in $STR will be removed, optional parameters for HTML and PHP code will be retained

The code written by the optional parameter.
such as: Echo Strip_tags ($text, ' <br><p> ');


Htmlspecialchars ($str [, Parameters]): page normal output HTML code parameter is the conversion method

11. Character Capitalization conversion function
Strtolower ($STR) string to lowercase
Strtoupper ($STR) string converted to uppercase
Ucfirst ($STR) converts the first character of a function to uppercase
Ucwords ($STR) converts the first letter of each word to uppercase

12. Database related functions
Addslashes ($STR): Make str within single quotes ('), double quotes ("), backslashes (\) and NUL

The string is converted to \ ', \ ', \ \.
MAGIC_QUOTES_GPC = on automatically escapes the contents of the Get post cookie

GET_MAGIC_QUOTES_GPC () detects whether to open MAGIC_QUOTES_GPC

Stripslashes () to remove the backslash in the string


13. Connection function
Implode (str, $arr) concatenate a string array by a specified character into a string; the implode () function has an individual name function join

addcslashes--to add a backslash escape character for some characters inside a string
addslashes--the characters inside a string in a specified manner
bin2hex--converts binary data to hexadecimal representations
chr--returns the ASCII code of a character
chunk_split--the string into small chunks by a certain character length
convert_cyr_string--converts Cyrillic characters to other characters
convert_uudecode--Decrypt A string
convert_uuencode--Encrypt a string
count_chars--returns the character usage information inside a string
crc32--computes a crc32 polynomial of a string
crypt--One-way hash encryption function
explode--converts a string into an array with a delimiter
fprintf--returns the data as required and writes directly to the document stream
get_html_translation_table--returns HTML entities that can be converted
Inverse function of the html_entity_decode--htmlentities () function to convert an HTML entity to a character
htmlentities--converts some characters in a string to an HTML entity
Inverse function of the htmlspecialchars_decode--htmlspecialchars () function to convert an HTML entity to a character
htmlspecialchars--converts some characters in a string to an HTML entity
implode--converts an array to a string with a specific delimiter
join--converts an array to a string, the alias of the Implode () function
levenshtein--calculates the difference size of two words
localeconv--get number-related format definitions
ltrim--removes whitespace from the left side of the string or the specified character
md5_file--a file for MD5 algorithm encryption
md5--the MD5 algorithm to encrypt a string
metaphone--to judge a string's pronunciation rules
money_format--the output of a number formatted according to the parameter
nl_langinfo--Query Language and local information
nl2br--replaces the newline character "\ n" in the string with "<br/>"
number_format--the output of a number formatted according to the parameter
ord--converts an ASCII code to a character
parse_str--converts a string in a format to a variable and a value
print--is used to output a single value
printf--to display data as required
quoted_printable_decode--encrypts a string into a 8-bit binary string
quotemeta--to escape several specific characters
rtrim--removes whitespace from the right side of the string or the specified character
setlocale--sets the local format for numbers, dates, and so on
sha1_file--a file for SHA1 algorithm encryption
sha1--the SHA1 algorithm to encrypt a string
similar_text--compares two strings and returns the number of similar characters considered by the system
soundex--to judge a string's pronunciation rules
sprintf--returns the data as required, but does not output
sscanf--can format strings
str_ireplace--matches and replaces strings like the Str_replace () function, but is case-insensitive
str_pad--the padding on both sides of the string
str_repeat--a string by repeating the combination
str_replace--Matching and replacement strings
str_rot13--string for ROT13 encryption processing
str_shuffle--a random order of characters inside a string
str_split--divides a string into an array by character spacing
str_word_count--gets the English word information inside the string
strcasecmp--size comparison of strings, case-insensitive
strchr--a partial strstr () function that returns a string by comparing the alias
strcmp--size comparison of strings
strcoll– size comparison of strings based on local settings
strcspn--returns the value of consecutive mismatched lengths of characters
strip_tags--removes HTML and PHP code from a string
stripcslashes--Inverse semantic addcslashes () function to escape processed strings
stripos--finds and returns the position of the first occurrence of the match, case-insensitive
stripslashes--Inverse semantic addslashes () function to escape processed strings
stristr--returns the part of a string by comparison, case-insensitive when compared
strlen--gets the encoded length of a string
strnatcasecmp--uses natural sorting to size a string, case-insensitive
strnatcmp--uses natural sorting to size a string comparison
strncasecmp--a size comparison of the first n characters of a string, case-insensitive
strncmp--size comparison of the first n characters of a string
strpbrk--returns a part of a string by comparing
strpos--finds and returns the location of the first occurrence
strrchr--returns the part of a string from a back-forward comparison
strrev--all the letters in the string in reverse order
strripos--looks up and returns the position of the first occurrence, matching case-insensitive
strrpos--looks up and returns the position of the first match from the back
strspn--matches and returns the value of the character's successive length
strstr--returns a part of a string by comparing
strtok--to split a string with a specified number of characters
strtolower--converts a string to lowercase
strtoupper--the string into uppercase
strtr--substitution for string comparisons
substr_compare--comparison of strings after they are intercepted
substr_count--calculate the number of occurrences of a character segment in a string
substr_replace--to replace part of a character in a string
substr--to intercept a string
trim--to remove whitespace or specified characters on either side of the string
ucfirst--converts the first letter of the given string to uppercase
ucwords--the first letter of each English word in the given string to uppercase
vfprintf--returns the data as required and writes directly to the document stream
vprintf--to display data as required
vsprintf--returns the data as required, but does not output
wordwrap--the string according to a certain character length



1, quickly create an array of functions range ()

For example, the range () function can quickly create an array of numbers from 1 to 9:

<?php
$numbers =range (1,9); Create a 9-digit array directly with range, ending with "1" starting "9" 1~9.
echo $numbers [1]; The second array value created by the output: 2; echo $numbers [0]; Enter the first value: 0.
?>

Of course, using range (9,1) creates a 9 to 1 array of numbers. At the same time, range () can also create an array of characters from A to Z:

<?php
$numbers =range (a,z);
foreach ($numbers as $mychrs)//Traverse $numbers Array, each loop the current cell value 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 an easy way to traverse an array, and foreach can only be used in arrays, and when you try to use it for other data types or an uninitialized variable, there are two forms:

foreach (array_expression as $value) Statementforeach (array_expression as $key => $value) statement
The first form traverses the given array_expression array. In each loop, the value of the current cell is assigned to the $value and the pointer inside the array moves forward one step (so the next cell will be taken in the next loop). The second format does the same thing, except that the key name of the current cell is also assigned to the variable in each loop $key


Note case when using a character array, such as range (A,Z) and range (A,Z) are different.

The range () function also has a third parameter, which is to set the step length, such as the array elements created by range (1,9,3) are: 1, 4, 7

Ordering of regular arrays in 2,php

The elements in a generic array are represented by characters or numbers, so you can sort the array elements in ascending order, the function is sort (). Like what:

<?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 that are sorted in ascending order are displayed as birth name Nation sex, and of course the sort () function is case-sensitive (letters from large to small) in the order that a ... Z...A...Z)

The Sort () function also has a second argument that shows whether ascending rules are used to compare numbers or strings. Like what:

<?php
echo "---sorted by number in ascending order---<br/>";
$num 2=array (' 26 ', ' 3 ',);
Sort ($num 2,sort_numeric);
foreach ($num 2 as $mychrs)
echo $mychrs. " ";

echo "<br/>---sorted by word Fu Shen order---<br/>";
$num 3=array (' 26 ', ' 3 ');
Sort ($num 3,sort_string);
foreach ($num 3 as $mychrs)
echo $mychrs. " ";
?>

Sort_numeric and sort_string are used to declare ascending order by number or character. If you are in ascending order of numbers: 3, 26, but if you follow the word Fu Shen order is: 26, 3.

In addition to ascending functions in PHP, there is a descending or backward-ordered function, which is the Rsort () function, such as:

$num 1=range (1,9);
Rsort ($num 1); This is actually equivalent to range (9,1)

Ordering of associative arrays in 3,php

In addition to supporting numeric indexed arrays, PHP supports related arrays. For example, the following array is a related (associative) array:

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

Using sort ($peoples) defaults to sort by the ascending order of the element definition values, you can use the Asort () function in an associative array to sort by element value in ascending order, and the most important of associative arrays is to sort by keywords (such as XM, XB, MZ, etc.) in ascending order, which is a function ksort ( function

<?php
$peoples =array (' xm ' => ' name ', ' xb ' => ' sex ', ' mz ' => ' nation ', ' cs ' => ' birth ');
foreach ($peoples as $mychrs)
echo $mychrs. " ";

echo "<br/>--sorted by element value in ascending order--<br/>";
Asort ($peoples);
foreach ($peoples as $mychrs)
echo $mychrs. " ";

echo "<br/>--in ascending order of keywords--<br/>";
Ksort ($peoples);
foreach ($peoples as $mychrs)
echo $mychrs. " ";
?>
And the regular array has the reverse sort rsort () descending function of the sort () ascending function, the associative array also has the corresponding descending function: the Asort () function and the Arsort () function, the Ksort () function, and the Krsort () function.
Memory: The prototype function is sort () where a, k indicates that associative array correlation must be predecessor, and the reverse sort uses the R modifier.

Random ordering of 4,php array elements

PHP uses the shuffle () function to randomly reorder the elements of an array, displaying different sorting combinations each time, such as:

<?php
$fer =array (' cnbruce ', ' cnrose ', ' cnjames ', ' Cnanne ');
Shuffle ($fer); The order is sorted, and a random order is made every time the page is refreshed.

foreach ($fer as $mychrs)
echo $mychrs. " ";
?>

5,php Array reverse sort in original order

You can use the Array_reverse () function in PHP to reverse the ordering of the array elements in their original order. Like what:

<?php
$fer =array (' cnbruce ', ' cnrose ', ' cnjames ', ' Cnanne ');
foreach ($fer as $mychrs)
echo $mychrs. " ";

$fer =array_reverse ($fer); Reverse sort the elements in an array in the original order
echo "<br/>--reverse--<br/> in original order";
foreach ($fer as $mychrs)
echo $mychrs. " ";
?>

Output:cnbruce cnrose cnjames Cnanne
--Reverse in original order--
Cnanne cnjames Cnrose Cnbruce

Note the $fer =array_reverse ($fer); Any sort function that precedes this is just declaring a reference and does not redefine the original array, but it needs to be redefined when I debug the function. This is because Array_reverse () is a modified copy of the original array, if you do not need an existing array, you can redefine the original array to achieve the purpose of overriding, otherwise you will define an array save copy, such as: $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.