PHP string function tutorial with instance code

Source: Internet
Author: User
Tags ereg explode flush ord sprintf string format strlen strtok

There are a lot of string functions in PHP Oh, it is said that PHP is composed of functions, which allows developers to speed up the development of the site Oh, well, crap don't say much. Let's take a look at my friends for free PHP string function tutorials and example code.

Addslashes: String add Slash.
Bin2Hex: The binary turns into 16 carry.
Chop: Remove continuous blank.
CHR: Returns the character of the ordinal value.
Chunk_split: Splits the string into small segments.
Convert_cyr_string: Converts the ancient Slavic string into other strings.
Crypt: Encrypts the string with DES encoding.
Echo: Output string.
Explode: Cut the string.
Flush: Clear out the output buffer.
Get_meta_tags: Extracts all meta tags from documents.
Htmlspecialchars: Converts special characters into HTML format.
Htmlentities: Converts all characters into an HTML string.
Implode: Converts an array into a string.
Join: Converts an array into a string.
LTrim: Remove continuous blank.
MD5: Computes the string of MD5.
NL2BR: Convert newline characters to <br>.
ORD: Returns the ordinal value of a character.
PARSE_STR: Parse query string into variables.
Print: Output string.
printf: Output format string.
Quoted_printable_decode: Converts the QP encoded string into a 8-bit string.
Quotemeta: Add reference symbol.
Rawurldecode: Revert from URL private format string to normal string.
Rawurlencode: Encodes a string into a URL-specific format.
SetLocale: Configure geographic information.
Similar_text: Computes string similarity.
Soundex: Calculating the pronunciation value of a string
sprintf: Format the string.
STRCHR: Find the first character that appears.
strcmp: string comparison.
STRCSPN: Length of different strings.
Strip_tags: Get rid of HTML and PHP tags.
Stripslashes: Remove backslash characters.
Strlen: Gets the string length.
Strrpos: Looks for the last occurrence of a character in the string.
Strpos: Looks for a character in the string to appear first.
STRRCHR: Gets the string at which a character last appears.
Strrev: Reverses the string.
STRSPN: Find out the number of strings that fall into another string mask.
Strstr: Returns the string from the beginning of a string to the end of the character string.
Strtok: Cut the string.
Strtolower: The string is all converted to lowercase.
Strtoupper: The string is all capitalized.
Str_replace: String substitution.
STRTR: Converts certain characters.
SUBSTR: Take a partial string.
Trim: Truncate the trailing space of the string.
Ucfirst: Capitalize the first character of the string.
Ucwords: Capitalize the first letter of each word in the string.


Let's look at an example of a PHP string function.

Josh@superfork.com (22-jun-1999) writes a function that converts 16 to binary.
?
function Hex2bin ($data) {
$len = strlen ($data);
for ($i =0; $i &lt; $len; $i +=2) {
$newdata. = Pack ("C", Hexdec (substr ($string, $i, 2));
}
return $newdata;
}
?>
return value: String
Function type: Data processing
Description: This function clears the continuous white space of the string.
Usage examples
?
$trimmed = Chop ($line);
?>
Reference: Trim ()
return value: String
Function type: Data processing
Description: This function converts the ordinal of a character to an ASCII character. This function is compared with Ord ().
Usage examples
?
$str. = Chr (27);
$str = sprintf ("End character of string:%c", 27);
?>
Reference: Ord () sprintf ()
return value: String
Function type: Data processing
Description: This function turns the character into a small paragraph for use by other functions. For example, Base64_encode. The default is to insert the end ("RN") of the parameter Chunklen (76 characters) every 76 characters. Returns a new string without altering the original string.
Usage examples
Format a string $data into a MIME BASE64 format
?
$new _string = Chunk_split (Base64_encode ($data));
?>
Reference: Ereg_replace ()
return value: String
Function type: Data processing
Description: This function turns the Cyrillic string into another string. The From and to two parameters are characters and represent the following meanings:
K-koi8-r
w-windows-1251
I-iso8859-5
a-x-cp866
d-x-cp866
M-x-mac-cyrillic
Syntax: String crypt (String str, string [salt]);
return value: String
Function type: Encoding processing
Description: This function encrypts the string with the standard UNIX encryption DES module. This is a one-way cryptographic function that cannot be decrypted. To compare strings, place the first two characters of the encrypted string in the salt's parameters, and then compare the encrypted string.
For more detailed information, refer to the crypt in UNIX Manual (man).
In some newer versions of UNIX, other encryption modules, such as MD5, are available in addition to DES. Even some systems use MD5 instead of DES. There are some changes in the salt parameters, which are determined by the length of the string passed to the Salt parameter:
Crypt_std_des-Standard DES encoding, enter 2-character salt.
Crypt_ext_des-Extended DES encoding, enter 9-character salt.
CRYPT_MD5-MD5 code, enter 12 characters plus $1$ salt.
Crypt_blowfish-Extended DES encoding, enter 16 characters plus $2$ salt.
In addition, if you do not use the salt parameter, the program is automatically generated.
return value: None
Function type: PHP system function
Description: This function outputs a string. Because it is not a real function, there is no return value.
Usage examples
<?php
echo "Hello World";
?>
Reference: Print () printf () flush ()
return value: Array
Function type: Data processing
Description: This function separator The string according to the specified string or character. Returns the cut string to the array variable.
Usage examples
?
$pizza = "The first piece of the second piece of the third piece of the sixth film";
$pieces = Explode ("", $pizza);
?>
Reference: Implode ()
return value: None
Function type: Data processing
Content Description: This function has no input and no output. Send out the data of the output buffer and clear it out.
Syntax: Array get_meta_tags (string filename, int [use_include_path]);
return value: Array
Function type: Data processing
Description: This function takes all the <meta ......> tags in the homepage and places the array variables back. For example
<meta content= "Pengwuchen" >
<meta content= "PHP BIBLE" >
<title>php bible</title>
This function finds the META tag, the string for the name attribute is an array index, and the Content property string is the data for the array. The note is that this function is the PHP native function, the UNIX series platform can not directly deal with the Macintosh file format, because the newline characters are different. Blake@mediaone.net points out (07-jun-1999) that the parameter filename can also be a URL, and the function pulls out the file meta tag of the remote server. When a function is processed, it encounters the end of the Syntax: String htmlspecialchars (String string);
return value: String
Function type: Data processing
Description: This function converts special characters into an HTML string format (&....;). The most commonly used occasions may be to deal with the message version of the customer message.
& (and) Convert to &
"(double quotes) into"
< (less than) turn into &lt;
> (greater than) convert to &gt;
This function converts only the special characters above, and does not convert all to the ASCII conversion specified by HTML.
Usage examples
This is the example provided by Aulbach@unter.franken.de (27-jan-1999)
<form action=bla>
Name of Restaurant:
<input type=text value= "&AMP;LT;?
echo Htmlspecialchars ($restname);?> "&gt;
<!--variable $restname is the $restname of sauces = "" The White Horse ""; -->
<BR>
Input description (if you will HTML, can be used directly): <BR>
<textarea ><?
echo Htmlspecialchars ($descript);
?></textarea>
<input type=submit>
</FORM>
Reference: Htmlentities () nl2br ()
Syntax: String htmlentities (String string);
return value: String
Function type: Data processing
Description: This function is a bit like the Htmlspecialchars () function, but this function converts all string characters to an HTML special character set string. However, after the conversion of reading the source code of the Web page, there will be a lot of trouble, especially the source code in the text will become unintelligible, the browser is still normal to see.
return value: String
Function type: Data processing
Description: This function combines the contents of an array into a string, and the parameter glue is a delimiter between words.
Usage examples
?
$colon _separated = Implode (":", $array);
echo $colon _separated;
?>
Reference: Explode () join () split ()
return value: String
Function type: Data processing
Description: This function is an alias for the implode function.
return value: String
Function type: Data processing
Description: This function is used to delete the continuous blank (whitespace) in the string.
Syntax: string MD5 (string str);
return value: String
Function type: Encoding processing
Content Description: This function is used to calculate MD5. For MD5 encoding, you can refer to RSA Data Security, Inc. MD5 message-digest algorithm. RFC1321, or Raixi pine, Freshfields, Zhang sincerity and so on with the modern cryptography and its application, 11.3.
Syntax: String nl2br (String string);
return value: String
Function type: Data processing
Description: This function converts line-wrapping characters into HTML line-wrapping <br> instructions.
Reference: Htmlspecialchars () htmlentities ()
return value: Integer
Function type: Data processing
Description: This function returns the ASCII (US National Standard Exchange code) ordinal value of the character. This function is the opposite of the Chr () function.
Usage examples
<?php
if (ord ($str) = = 10) {
The first word of echo ("string $str is a newline character. n ");
}
?>
Reference: Chr ()
Syntax: void Parse_str (String str);
return value: None
Function type: Data processing
Content Description: This function can parse the query_string string of the Get method returned by the browser. The variable name and value returned depend on the name and value of the query_string.
Usage examples
<?php
$str = "First=value&second[]=this+works&second[]=another";
Parse_str ($STR);
Echo $first; Display the "value" string
echo $second [0]; Display the "This Works" string
echo $second [1]; Display the "another" string
?>
Return Value: Boolean value
Function type: Data processing
Content Description: This function output string. If successful, return 1, failure returns 0. For example, when the client's browser suddenly hangs, it will cause the output to fail.
Reference: Echo () printf () flush ()
return value: Integer
Function type: Data processing
Description: This function formats the string according to the content format specified by the parameter format. Details of the format can be referred to sprintf ().
Reference: Print () sprintf () flush ()
Syntax: string quoted_printable_decode (String str);
return value: String
Function type: Encoding processing
Description: This function can decode the quoted-printable string into a 8-bit encoded string. And this function is similar to the Imap_qprint () function, only a different place is to use the Imap_qprint () function requires the system to join the IMAP module, and this function does not need an IMAP module.
return value: String
Function type: Data processing
Content Description: This function will contain the string. \ + * ? [ ^ ] ($) Precede the character with a backslash "" symbol.
Reference: Addslashes () htmlentities () Htmlspecialchars () nl2br () stripslashes ()
Syntax: string rawurldecode (String str);
return value: String
Function type: Encoding processing
Content Description: This function decodes a string. From a string-specific format of the URL to a normal string. Detailed coding and decoding information and specifications can be referenced in RFC 1738.
Reference: Rawurlencode ()
Syntax: string rawurldecode (String str);
return value: String
Function type: Encoding processing
Description: This function encodes a string into a string-specific format for a URL, and special characters are converted to a percent symbol followed by a two 16-digit format. For example, the space will become% 20.
Usage examples
<?php
Echo ' &lt;a href= ' ftp://guest: ', Rawurlencode (' foo @+%/'), ' @localhost/x.txt ' >;
?&gt;
Reference: Rawurldecode ()

return value: String
Function type: Operating system and environment
Content Description: This function is used to configure the local information. Parameter category has the following choices:
Lc_all includes all of the following options.
Lc_collate configuration string comparison, PHP is not yet implemented to make this entry.
Lc_ctype Configure character categories and conversions. For example, all uppercase Strtoupper ().
Lc_monetary To configure the financial currency, PHP is not yet implemented.
Lc_numeric configures the number of digits after the decimal point.
Lc_time Configure the time date format to be shared with strftime ().
If the parameter locate is an empty string "", the value of the locate or LANG of the system environment variable is used. If locate is zero, the geographic configuration is not changed. Returns a new region and returns False if the system is not already implemented.
Usage examples
Michal Fita <manveru@witrynka.pl> at 11-jan-1999 11:01 presented this example of the localization of Poland.
?
SetLocale ("Lc_all", "pl");
$net = "1234,56";
$gross = "1,22" * $net;
printf ("Gross margin:%s, net profit:%s", $gross, $net);
* Poland Total/font>[Value tax is 22% * *
?&gt;
The return value is
Gross margin: 1234, 56, net profit: 1506,1632
return value: Integer
Function type: Data processing
Content Description
This function is used to calculate the similarity between two strings.
return value: String
Function type: Data processing
Content Description: Soundex value is the use of English word pronunciation approximation value of the value, the value is composed of four characters, the first character is an English letter, the latter three digits. In the phonetic alphabet sometimes there will be read but can not spell the correct word, especially in the search engine in the face of the incoming English string, you can use this function to do a similar effect of fuzzy comparison. For example Knuth and Kant two strings, their soundex values are H416. A more detailed reference to Donald Knuth's masterpiece: The Art of computer program design (the arts of Computer programming) the third volume sorting and searching.
Usage examples
?
$str 1=soundex ("Wilson");
$str 2=soundex ("Waillsume");
echo "Soundex (" Wilson ") = $str 1 equals n";
echo "Soundex" ("waillsume") = $str 2n ";
echo "Value is $str 1";
?>
The string returned by the previous example is
Soundex ("Wilson") =w425 equals
Soundex ("Waillsume") =w425
Values are W425
return value: String
Function type: Data processing
Content Description: This function is used to format strings. The parameter format is the format of the transformation, starting with the percent sign to the converted character. The format of the conversion is included in the
The blank character. 0, the space is filled 0, the space is the default value, which means that the space is placed.
The Alignment method. The default value is aligned to the right, and the minus table is left-aligned.
The field width. is the minimum width.
Accuracy. Refers to the number of floating-point digits after the decimal point.
Type, see the following table% print percent symbol, do not convert.
The b integer is converted into binary.
The c integer is converted to the corresponding ASCII character.
The d integer is turned into 10.
The F times the precision number is converted to floating point numbers.
The o integer is converted into octal.
The s integer turns into a string.
The x integer is converted to lowercase 16.
The X integer is converted to uppercase 16.
Usage examples
?
$money 1 = 68.75;
$money 2 = 54.35;
$money = $money 1 + $money 2;
At this time the variable $money value is "123.1";
$formatted = sprintf ("%01.2f", $money);
At this point the variable $ formatted value is "123.10"
?>
return value: String
Function type: Data processing
Content Description: This function is the STRSTR () function.
return value: Integer
Function type: Data processing
Content Description: This function is used to compare the size of two strings. Returns a negative number indicating that the str1 is less than str2; Returns a positive number indicating that the STR1 is greater than str2, and zero indicates the same two strings.
Reference: Ereg () substr () strstr ()
return value: Integer
Function type: Data processing
Description: This function is used to compare two strings and to calculate the length of strings at different points.
Reference: STRSPN ()
Syntax: string strip_tags (String str);
return value: String
Function type: Data processing
Description: This function can remove any HTML and PHP tag strings contained in the string. If the HTML and PHP tags of the string are original errors, such as less than the symbol greater than, it will return an error. This function has the same function as FGETSS ().
return value: String
Function type: Data processing
Description: This function can remove the backslash characters in the string. If you have two consecutive backslashes, remove one and leave one. If there is only one backslash, remove it directly.
Reference: Addslashes ()
return value: Integer
Function type: Data processing
Content Description: This function returns the specified string length.
return value: Integer
Function type: Data processing
Description: This function is used to find the last occurrence of the character needle in the string haystack. It is worth noting that needle can only be a single character, Chinese characters and so on is not suitable. Returns a value of False if the specified character is not found.
Reference: Strpos () STRRCHR () substr () strstr ()
return value: Integer
Function type: Data processing
Description: This function is used to find the first occurrence of the character needle in the string haystack. It is worth noting that needle can only be a single character, Chinese characters and so on is not suitable. Returns a value of False if the specified character is not found. The parameter offset can be omitted and used for Y to indicate the start of offset.
Reference: Strrpos () STRRCHR () substr () strstr ()
return value: Integer
Function type: Data processing
Description: This function is used to find the last occurrence of the character needle in the string haystack, and to return the string from this position to the end of the string haystack. Returns False if needle is not found.
Usage examples
The following example retrieves the last path of the environment variable path
<?php
$dir = substr (STRRCHR ($PATH, ":"), 1);
echo "The Last path is:". $dir;
?>
Reference: substr () strstr ()
return value: String
Function type: Data processing
Content Description: Reverse the string backwards.
Usage examples
The following example returns a string of "Gnep Nosliw"
?
$str =strrev ("Wilson Peng");
Echo $str;
?>
return value: Integer
Function type: Data processing
Description: This function str2 the string as a mask, which can be used to compute that several characters in the STR1 string fall into the str2 mask.
Reference: STRCSPN ()
return value: String
Function type: Data processing
Description: This function returns needle the string that first appears at Haystack to the end of haystack. Returns False if needle is not found.
Reference: STRRCHR () substr () Ereg ()
return value: String
Function type: Data processing
Description: This function cuts the string arg1 the string arg2 into small segments.
Use Example: This example uses the I will is back string to be cut in blank.
<?php
$string = "I'll be is back";
$tok = Strtok ($string, "");
while ($tok) {
echo "word = $tok &lt;br>";
$tok = Strtok ("");
}
?&gt;
Reference: Split () explode ()
return value: String
Function type: Data processing
Description: This function changes the string str all to lowercase strings.
Reference: Strtoupper () Ucfirst ()
return value: String
Function type: Data processing
Description: This function converts the string str to all uppercase strings.
Reference: Strtolower () Ucfirst ()
return value: String
Function type: Data processing
Description: This function replaces the string str into the haystack string and replaces all needle with Str. Mlevine@adtraq.com (11-apr-1999) points out that in the PHP 3.0.7 version, this function has some bugs, and nadeem@bleh.org (05-jun-1999) complements the PHP 3.0.8 version function and returns to normal.
Usage examples
The following example replaces%body% with black
<?php
$bodytag = Str_replace ("%body%", "Black", "&lt;body text=%body%>");
Echo $bodytag;
?&gt;
Reference: Ereg_replace ()
return value: String
Function type: Data processing
Description: This function converts the string str to the character one by one to.
Reference: Ereg_replace ()
return value: String
Function type: Data processing
Description: This function extracts the length character of the string from the start of string strings. If start is a negative number, it is counted from the end of the string. If the parameter length that can be omitted exists but is negative, it is taken to the penultimate length character.
Usage examples
?
echo substr ("abcdef", 1, 3); Return "BCD"
echo substr ("ABCdef",-2); Return to "EF"
echo substr ("ABCdef",-3, 1); Return "D"
echo substr ("abcdef", 1,-1); Return to "BCDE"
?>
Reference: STRRCHR () Ereg ()
return value: String
Function type: Data processing
Description: This function returns the string string after the white space character is removed.
Reference: Chop () LTrim ()
return value: String
Function type: Data processing
Content Description: This function returns the string str the first letter of the word is converted to uppercase.
Reference: Strtoupper () Strtolower ()
return value: String
Function type: Data processing
Description: This function returns the string str the first letter of each word is changed to uppercase.


1) echo,print,printf,sprintf

The first two functions are output strings. If a variable name is substituted in the string, it is replaced with its value.

The latter two functions are similar to C's with the same name function.

(2) Strchr,strlen,strtok,strrchr,strrev,strstr,strtolower,

Strtoupper,substr,ucfirst

These are commonly used string manipulation functions, some of which have exactly the same meaning as the functions of the same name in C.

Strrev is to flip a string.

The meaning of Strtolower and strtoupper should not be explained.

Ucfirst the first character of a string into uppercase.

SUBSTR is a substring of the return string, using the following: substr (string, header, length).

The head position is from 0. If it's a negative number, it's from the tail forward.

(3) Chr,ord

Similar to C's function of the same name.

(4) Explode,implode,join

These are the functions that are related to the array.

Explode (string, delimiter) returns an array of characters that are produced by separating the string from the separator.

Implode (array, delimiter) returns a string that inserts a delimiter between the elements of an array.

Join has the same meaning as implode.

(5) Chop

Removes whitespace from the tail of the string.

(6) Htmlspecialchars

Replace the HTML special characters in the string with their names, for example, "to".

(7) NL2BR

Precede each carriage return in the string with a "
".

(8) Addslashes,stripslashes

Add and remove "\" for characters in the string that need to be added "\" to the database query.

(9) Parse_str

Parse the string "Name1=value1&name2=value2& ..." into some variables.

For example:
Parse_str ("a=1&b=2");

Generates A and B two variables with a value of 1,2 respectively.

If there are two names that are part of the same name/value, then the last value overrides the previous one.

If both pairs have "[]" at the end, such as "a[]=1&a[]=2", the array A is generated, and two elements are 1,2

Okay, so the article's written a lot, and hopefully the examples of these string functions will help you.

Related Article

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.