PHP String Functions

Source: Internet
Author: User
Tags crc32 format definition ord rtrim sha1 shuffle strcmp
1 Find the character position function:
Strpos ($str, Search,[int]): Find the first position of search in $str starting with int;
Stripos ($str, search,[int]): function returns the position of the first occurrence of a string 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. Extracting sub-character functions (double-byte)
Submit ($str, int start[,int length]): Extracts [length string] from strat position in $str.
Strstr ($str 1, $str 2): Searches for $str2 from $STR1 (the first position) and intercepts the end string from it, or false if none.
The Stristr () function is the same as STRSTR, but is not case sensitive.
STRRCHR () prompt returned from the last word searched; use: Fetch the file name in the path

3. Replace string
Str_replace (Search,replace, $str): Find search from $STR Replace with replace

Str_irreplace (Search,replace, $STR):

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

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

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

4. Character length
int strlen ($STR)

5. Compare character functions
int strcmp ($str 1, $str 2): $str 1&gt;=< $str 2 are positive 1,0,-1 (string comparison)
STRCASECMP () ditto (no case)

STRNATCMP ("4", "14") compare strings by natural sort
STRNATCASECMP () ibid. (case sensitive)

6. Dividing the array function
Str_split ($str, Len): Splits the $STR by Len length returns the array
Split (search, $str [, int]): Splits the $str by the search character returns the array int is split several times, the back will not be split
Expload (Search, $str [, int])

7, remove the space: LTrim, RTrim, Trim

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

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

10. HTML code related functions

NL2BR (): Make/n convert to &lt;br>.

Strip_tags ($str [, ' <p> ']): Remove HTML and PHP tags
In $str all HTML and PHP code will be removed, and the optional parameters for HTML and PHP code will be preserved

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


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

11. Character Case Conversion function
Strtolower ($STR) string converted 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 the single quotation mark ('), double quotation mark ("), backslash (/), and NUL in Str

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

GET_MAGIC_QUOTES_GPC () detects if MAGIC_QUOTES_GPC is turned on

Stripslashes () to remove backslashes from a string


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

addcslashes--adds a backslash escape character for some characters inside a string
addslashes--characters inside a string are escaped in the specified manner
bin2hex--converts binary data to hexadecimal notation
chr--returns the ASCII code of a character
chunk_split--divide a string into small pieces at a certain length of character
convert_cyr_string--converting Slavic characters to other characters
convert_uudecode--decrypting a string
convert_uuencode--Encrypt a string
count_chars--returns the character usage information for a string
crc32--computes a crc32 polynomial of a string
crypt--one-way hash encryption function
explode--converts a string into an array form with a separator
fprintf--returns data as required and writes directly to the document stream
get_html_translation_table--returning HTML entities that can be converted
Inverse of the html_entity_decode--htmlentities () function to convert HTML entities to characters
htmlentities--convert some characters in a string to HTML entities
Inverse of the htmlspecialchars_decode--htmlspecialchars () function to convert HTML entities to characters
htmlspecialchars--convert some characters in a string to HTML entities
implode--to convert an array to a string with a specific separator character
join--convert an array to a string, alias of the Implode () function
levenshtein--Calculate the difference size of two words
localeconv--getting a number-related format definition
ltrim--to remove whitespace to the left of a string or to a specified character
md5_file--a file for MD5 algorithm encryption
md5--a string for MD5 algorithm encryption
metaphone--judging the pronunciation rules of a string
money_format--output of numbers formatted according to parameters
nl_langinfo--querying language and local information
nl2br--Replace the newline character "/n" in the string with "<br/>"
number_format--output of numbers formatted according to parameters
ord--converts an ASCII code to one character
parse_str--Convert a string of a certain format into a variable and a value
print--used to output a single value
printf--data Display as required
quoted_printable_decode--to encrypt a string into a 8-bit binary string
quotemeta--to escape a number of specific characters
rtrim--remove whitespace to the right of a string or a specified character
setlocale--setting local formats for numbers, dates, and so on
sha1_file--a file for SHA1 algorithm encryption
sha1--a string for SHA1 algorithm encryption
similar_text--compares two strings and returns the number of similar characters that the system thinks
soundex--judging the pronunciation rules of a string
The sprintf--returns the data as required, but does not output
sscanf--can format a string
str_ireplace--matches and replaces strings like the Str_replace () function, but is case insensitive
str_pad--padding on both sides of a string
str_repeat--repeating combinations of strings
str_replace--matching and replacing strings
str_rot13--string for ROT13 encryption processing
str_shuffle--random ordering of characters inside a string
str_split--splits a string into an array by character spacing
str_word_count--get the English word information inside the string
strcasecmp--size comparison of strings, case insensitive
strchr--the alias of a partial strstr () function that returns a string by comparison
strcmp--size comparison of strings
strcoll– size comparison of strings based on local settings
strcspn--returns the value of a continuous non-matching length of characters
strip_tags--remove HTML and PHP code from a string
stripcslashes--inverse literal addcslashes () function escapes processed strings
stripos--finds and returns the position of the first occurrence, matching is case-insensitive
stripslashes--inverse literal addslashes () function escapes processed strings
stristr--returns a portion of a string by comparison, case-insensitive compared
strlen--gets the encoded length of a string
strnatcasecmp--the size comparison of strings using natural sorting, case-insensitive
strnatcmp--the size comparison of strings using the natural sort method
strncasecmp--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 portion of a string by comparison
strpos--Find and return the position of the first occurrence
strrchr--returns a part of a string by comparing it from backward to forward
strrev--all letters inside the string in reverse order
strripos--finds and returns the position of the first match from the back, matching is case insensitive
strrpos--Find and return the position of the first match from behind
strspn--matches and returns the value of the character continuous occurrence length
strstr--returns a portion of a string by comparison
strtok--to split a string with a specified number of characters
strtolower--converting a string to lowercase
strtoupper--converting a string to uppercase
strtr--to string comparison substitution
substr_compare--Comparison of strings after interception
substr_count--count 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--remove whitespace or specified characters on either side of a string
ucfirst--converts the first letter of a given string to uppercase
ucwords--the first letter of each English word of the given string into uppercase
vfprintf--returns data as required and writes directly to the document stream
vprintf--data Display as required
The vsprintf--returns the data as required, but does not output
wordwrap--to divide a string by a certain character length

1, quickly create an array of function range ()

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

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

Of course, using range (9,1) creates an array of numbers from 9 to 1. Also, range () can create an array of characters from A to Z:

<?php
$numbers =range (a,z);
foreach ($numbers as $mychrs)//Traversal $numbers array, each time the current cell value of the 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 an easy way to iterate through an array, and foreach can only be used with arrays, and when it tries to use it for other data types or an uninitialized variable, it produces an error, which has two forms:

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


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

The range () function also has a third argument that sets the step size, such as the array element created by range (1,9,3): 1, 4, 7

Ordering of regular arrays in 2,php

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

<?php
$people =array (' name ', ' Sex ', ' nation ', ' birth ');
foreach ($people as $mychrs)
echo $mychrs. " ";
Sort ($people);
echo "<br/>---after sorting---<br/>";
foreach ($people as $mychrs)
echo $mychrs. " ";
?>

An ascending sorted array element is displayed as birth name Nation sex, of course, the sort () function is case-sensitive (Letters from the largest to smallest order are: A ... Z...A...Z)

The Sort () function also has a second argument that indicates whether the ascending rule is used to compare numbers or strings. Like what:

<?php
echo "---sort---<br/> in ascending order of numbers";
$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 in ascending order of numbers or characters. If the numbers are sorted in ascending order: 3, 26, but if ordered by word Fu Shen: 26, 3.

In addition to the ascending function in PHP, there are functions in descending or reverse order, that is, the Rsort () function, such as:

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

Ordering of associative arrays in 3,php

In addition to supporting numeric index 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 ');

By default, the sort ($peoples) is sorted by the ascending order of the element-defined values, and the Asort () function is used in the associative array to indicate ascending order by element value, and the most important of the associative array is to sort by the ascending order of the keywords (such as XM, XB, MZ, etc.) by using the function Ksort ( function

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

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

echo "<br/>----<br/> In ascending order of keywords";
Ksort ($peoples);
foreach ($peoples as $mychrs)
echo $mychrs. " ";
?>
And the regular array has the sort () ascending function of the inverse sort rsort () for the descending function, the associative array also has a 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 pre-ordered, and reverse sort is used with r adornments.

4,php array element Random ordering

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

<?php
$fer =array (' cnbruce ', ' cnrose ', ' cnjames ', ' Cnanne ');
Shuffle ($fer); The order is sorted, and the page is randomly sorted once per refresh.

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

5,php arrays are reversed in the original order

In PHP, you can use the Array_reverse () function to reverse the order of the array elements in the original sequence. Like what:

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

$fer =array_reverse ($fer); Reverses the elements in the array in the original order
echo "<br/>--reverse--<br/> 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 here the $fer =array_reverse ($fer); Any sort function prior to this is simply declaring the reference and not redefining the original array, but I need to redefine it when I debug the function. This is because Array_reverse () is returning the modified copy of the original array, if the original array is not needed, the original array can be redefined to achieve the purpose of overwriting, otherwise define the 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.