PHP String Manipulation Learning Notes

Source: Internet
Author: User
Tags crypt explode rtrim strcmp

Because PHP is a weak language type, when using a string manipulation function, other types of data are treated as strings.

First, the string definition and display

Strings are marked by single quotes, double quotes, which treat all characters in single quotes as characters, while the latter is not.

The display of strings can be distinguished by using the Echo () and print () functions, which differ: print () has a return value, returns 1, and Echo () does not, so Echo () is faster than print (), and print () can be applied to compound statements, and Echo () cannot. In addition, echo can output multiple strings at a time, while print cannot.

Second, the formatting of the string

The function printf () outputs a string created from a replacement value to a format string in the following syntax format:

int printf (string $format [, mixed $args])

The first parameter, $format, is the format string, $args is the value to replace, the character "%" in the format string indicates a replacement token.

Each replacement tag in the format string consists of a percent sign, followed by a fill character, an alignment character, a field width, and a type specifier. The type descriptor for the string is "s".

All conversion instructions start with a "%", and if you want to print a "%", you must use "percent". The padding character indicates that the character is used to fill the result, make the result a string of the appropriate size, use a space padding by default, and that the alignment character has a different effect on the string and array, and that for the string, the minus "-" aligns the string to the right (by default to left), plus "+" for the number. Make positive numbers start with a plus sign at the time of the output; The field width is the width of the string that should be output, and if the actual length of the string is less than that, the padding character is used, and the type specifier represents the type of data to be converted in the value to be replaced.

The function sprintf () takes the same parameters as the printf () function, but returns a built-in string that allows the string to be stored in a variable for later use.

The function vprintf () allows an array to be used as a parameter after the format, and the usage is basically the same as the printf () function.

The function vsprintf () and the vprintf () function can use an array as an argument, but not a string.

Three, commonly used string functions

1. Calculating string Lengths

Strlen () function: int strlen (string $string)

The function returns the length of the string, the 1 English characters are 1 characters long, 1 Chinese characters are 2 characters long, and the spaces in the string are counted as one character.

2. Change the string to case

The Strtolower () function converts all strings to lowercase, using the Strtoupper () function to convert all strings to uppercase.

The Ucfirst () function changes the first character of a string to uppercase, and the Ucwords () function converts the first letter of each word in the string to uppercase.

3. String clipping

The LTrim (), RTrim (), trim () functions are used to delete the leftmost, rightmost, and both sides of a string with the specified character, and return the remaining string.

String Trim (String $str [, String $charlist])

String RTrim (string $str [, String $charlist])

String LTrim (string $str [, String $charlist])

Default delete characters for trim, LTrim, RTrim functions

Character ASCII code Significance
"" (0x20) Space
"\ T" 9 (0x09) Tabs
"\ n" Ten (0x0A) Line break
"\ r" (0x0D) Enter
"The" 0 (0x00) Empty bytes
"\X0B" One (0x0B) Vertical tab

4. Searching for strings

The Strstr () function and the Stristr () function, both function and return values are the same, except that the STRISTR () function is case insensitive.

Syntax format for the STRSTR () function: String Strstr (String $haystack, String $needle)

The Strstr () function is used to find the position where the string pointer $needle appears in the string $haystack and returns the string from $needle to the end of the $haystack string in the $haystack string. If there is no return value and no $needle is found, false is returned. The Strstr () function also has a function strchr () with the same name.

5. String and ASCII code

Use the Ord () function to return the ASCII code of the character, or use the Chr () function to return the ASCII code corresponding to the character.

Iv. Comparison of strings

The comparison is primarily a comparison of the type and case of a string. A comparison of strings can be used with the comparison operator "= =", "! = "," = = = ","! = = "To compare, you can also use a comparison function to compare.

Use "! = "=" and "= =" Compare two objects do not necessarily have type equality, integer type can also be compared with string. and "! = = "and" = = = "The object type to compare is exactly the same, which may return true.

Common string comparison functions are: strcmp (), strcasecmp (), strncmp (), and strncasecmp (). The syntax format is as follows:

int strcmp (String $str 1,string $str 2)

int strcasecmp (String $str 1, String $str 2)

int strncmp (string $str 1,string $str 2,int $len)

int strncasecmp (string $str 1,string $str 2,int $len)

All four functions are used to compare the size of a string, and if $STR1 is larger than $STR2, they all return integers greater than 0, and if $STR1 is smaller than $str2, an integer less than 0 is returned, or 0 if the two are equal.

The difference is that the strcmp () function is used for case-sensitive string comparisons; the strcasecmp () function is used for case-insensitive comparisons; the strncmp () function is used to compare parts of a string, starting from the beginning of the string, $len is the length to compare The strncasecmp () function, like the strncmp () function, is simply not case-sensitive.

V. Substitution of strings

The substitution of strings refers to replacing related characters in the original string with the specified string to form a new string to meet the new requirements.

Commonly used is the str_replace () function, which has the following syntax:

Mixed Str_replace (mixed $search, mixed $replace, mixed $subject [, int & $count])

The Str_replace () function replaces the $search string in the string $subject with the new string $replace. $count is an optional parameter that represents the number of substitution operations to perform.

The Str_replace () function is case-sensitive and can implement many-to-one, many-to-many replacements, but cannot implement a-to-many substitution.

When using a many-to-many substitution, the elements in the first array are replaced by the corresponding elements in the second array, and if one array has fewer elements than the other, the less part is treated as empty.

The Substr_replace () function implements the substitution string as part of the syntax format:

Mixed Substr_replace (mixed $string, string $replacement, int $start [, int $length])

The parameter $string is the original string, $replacement is the string to replace.

$start is the offset at which to begin the replacement, calculated from 0, if 0 or a positive value, is the offset calculated from the beginning of the string, or, if negative, the offset from the end of the string.

The $length is an optional parameter that represents the length to be replaced, if not given from the $start position until the end of the string, and if $length is 0, the replacement string is inserted into the original string, or if the $length is positive, the string replaced with the replacement string Chengdu; Length is a negative value, indicating that the substitution is stopped from the end of the string to $length characters.

Six, string and HTML

1. Convert characters to HTML entity form

The function htmlspecialchars () converts a character into an entity form of HTML.

Special characters that can be converted to HTML entities

Original character Character name Converted Characters
& and notation &
" Double quotes "
Single quotation marks & #039;
< Less than sign &lt;
> Greater than sign &gt;

The syntax format for the Htmlspecialchars () function is as follows:

String Htmlspecialchars (string $string [, int $quote _style[,string $charset [, BOOL $double _encode]])

The parameter $string is the string to be converted, $quote _style, $charset, and $doublt_encode are optional parameters. $quote _style Specifies how to convert single and double quote characters, the values can be Ent_compat (default, convert double quotes only), ent_noquotes (neither convert), and ent_quotes (both convert). The $charset is a character set and defaults to Iso-859-1. Parameter $double_encode is not converted to HTML entity if False, the default is True

The Htmlentities () function can also convert special characters to entities, but the Htmlspecialchars () function converts only the 5 characters of &, ",", <, >, and the Htmlentities () function converts the kanji.

2. Convert HTML entity form to special character

Use the Htmlspecialchars_decode () function to convert the entity form of HTML into HTML format, and the Html_entity_decode () function converts all HTML entity forms to HTML

3. Conversion of newline characters

Using "\ n" in an HTML file to display HTML code without the effect of wrapping, you can use the NL2BR () function, which uses the "<br/>" tag in HTML instead of the line break "\ n" in the string.

Vii. Other String functions

1. Strings and Arrays

(1) String conversions to arrays

Use the explode () function to split another string with the specified string and return an array.

Array explode (string $separator, string $string [, int $limit])

This function returns an array of strings, each of which is a substring of $string, separated by the string $separator as a boundary point.

If the $limit parameter is set, the returned value contains a maximum of $limit elements, and the last element will contain the remainder of the $string. If the $limit parameter is negative, all elements except the last-$limit element are returned.

If the parameter $separator is an empty string (""), the Explode () function returns False, and if $separator contains a value that is not found in $string, the Explode () function returns an array containing a single element of $string.

(2) array converted to string

Use the implode () function to concatenate strings in an array into a string

String implode (string $glue, array $pieces)

$pieces is the array that holds the string to concatenate, $glue is the connector used to concatenate strings.

The implode () function also has an alias, the join () function.

2. String encryption function

The crypt () function completes the encryption function

String crypt (String $str [, String $salt])

This function completes the one-way encryption function, that is, once the string is encrypted, it cannot be converted into its original form. The $str in the function is a string that needs to be encrypted, and the second optional parameter, $salt, is a bit string that can affect the cryptographic cipher and further eliminate the possibility of attacking.

For greater security, you can use the MD5 () function, which uses the MD5 hashing algorithm to convert a string to a unique string of 32 bits long, which is irreversible.

This article is from the "Rangers" blog, please be sure to keep this source http://ccnupxz.blog.51cto.com/8803964/1834469

PHP String Manipulation Learning Notes

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.