Introduction to PHP string manipulation functions

Source: Internet
Author: User
Tags arrays explode file upload function prototype php file upload strcmp strlen trim

PHP Tutorial String manipulation function Introductory article
1. Definition and display of strings
Definition: By "", "" to mark
Displays: Echo () and print (), but print () has a return value of 1, and Echo () does not, but Echo is faster than print () and print () can be used in compound statements.
2. Formatting of strings
printf (String $format [, Mixed$args])
The first parameter is the format string, $args is the value to be replaced, Prinf ("%d", $num);
Description, if you want to print a "%", you must use "%", floating-point number F, octal system with "0"
3. Commonly used String functions
1. Calculate the length of a string
Strlen (string $string), indicating that the length of 1 English characters, 1 characters in length of 2 characters, and space is counted as a character.
2. Change the case of a string
Convert to lowercase: strtolower ()
Convert to upper case: Strtoupper ()
Capitalize the first character: Ucfirst ()
Capitalize the first letter of each word ucwords ()
3. String clipping.
When the end of a string has extra whitespace characters, such as spaces, tabs, etc. can be used
String Trim (String $str [, String $charlist])
String RTrim (String $str [sring $charlist])
String Itrim (String $str [, String $charlist])
Table 4.1 default deletion characters for trim, Itrim, RTrim functions
Characters
ASCII code
Significance

" "
(0x20)
Space

"T"
9 (0x09)
Tabs

N
Ten (0x)
Line Wrap

"R"
(0x0D)
Enter

""
0 (0x00)
Empty bytes

"X0B"
One (0x0b)
Vertical tab

4. Find the string
String Strstr (String $a, string $b)
Description: The Strstr () function is used to find the position where the string pointer $b appears in the string $a.
and returns the string from $b to the end of the $a string in the $a string.
Returns False if there is no return value, that is, no $b is found. The Strstr () function also has a function named STRCHR () with the same name.
5. String and ASCII code
4. Comparison of strings
Comparison functions have
strcmp ()//Case Sensitivity
STRCASECMP ()//case-insensitive
STRNCMP ()//comparison section
STRNCASECMP ()//case-insensitive, Comparison section
5. Replacement of strings
Str_replace (Search,replace,subject)
Description use the new string replace to replace the search string in the subject string
<?php
$str = "I Love You";
$replace = "Lucy";
$end =str_replace ("You", $replace, $STR);
Echo $end; Output "I Love Lucy"
?>
For case sensitivity, you can also implement a one-to-many, many-to-many substitution, but cannot achieve a one-to-many replacement.
<?php
$str = "What is Your Name";
$array =array ("A", "O", "a", "O", "E");
Echo Str_replace ($array, "", $str); Multi-pair substitution, output "Wht is Yur Nm"
$array 1=array ("A", "B", "C");
$array 2=array ("D", "E", "F");
Echo Str_replace ($array 1, $array 2, "abcdef"); Multi-pair substitution, output "defdef"
?>
Substr_replace
Replaces part of a string.
6. Strings and HTML
Slightly
7. Other String functions
1. Strings and Arrays
A. String conversions to arrays
The explode () function can split another string with the specified string and return an array
<?php
$str = "Split string using spaces";
Array=explode ("", $str);
Pint_r ($array);
Output array ([0] => use [1] => space [2] => split [3] => string)
?>
B. Array conversion to string
Implode (string $glue, array $pieces)
$pieces is an array of strings to be concatenated, $glue is the connector for the connection string. For example:
<?php
$array =array ("Hello", "how", "are" and "you");
$str =implode (",", $array); Use commas as connectors
Echo $str; Output "Hello,how,are,you"
?>
C. Cryptographic functions for strings
MD5 (); Crypt (), but this function cannot be converted to its original form once it has been encrypted.
4.3 Instance message thin content processing
A guest book, the guestbook has email address and the user's message, extracts the customer's email address and the message, requests the email address in the @ symbol before cannot be a bit "." or comma ",".
The email address at the @ symbol before the content as the user's user name, and the user's message in the first person "I" modified to "I".
Copy code code as follows:
<form name= "F1" method= "post" action= "" >
<font face= "founder Shu Body" size=4> Your email address:</font><br>
<input type= "text" name= "Email" size=31><br>
<font face= "founder Shu Body" size=4> your message:</font><br>
<textarea name= "Note" rows=10 cols=30></textarea>
<br><input type= "Submit" Name= "BT1" value= "submitted" >
<input type= "reset" name= "BT2" value= "Empty" >
</form>
<!--above is the guest book form-->
<?php
if (Isset ($_post[' bt1 '))
{
$Email =$_post[' Email ']; Receive Eamil Address
$note =$_post[' note ']; Receive Message
if (! $Email | |! $note)//Determine if the value is obtained
echo "<script>alert (' email address and message please fill in complete!") ') </script>;
Else
{
$array =explode ("@", $Email); Split email Address
if (count ($array)!=2)////If two @ sign is an error
echo "<script>alert (' email address format is wrong!) ') </script>;
Else
{
$username = $array [0]; Get the content before the @ symbol
$netname = $array [1]; Get the content after the @ symbol
If the username contains the "." Or "," the error
if (Strstr ($username, ".") or Strstr ($username, ","))
echo "<script>alert (' email address format is wrong!) ') </script>;
Else
{
$str 1= Htmlspecialchars ("<"); Output symbol "<"
$str 2= htmlspecialchars (">"); Output symbol ">"
Replace "I" with "I" in the message
$newnote =str_replace ("I", "I", $note);
echo "<font face= ' bold ' size=4>";
echo "User". $str 1. $username. $str 2. "Hello!";
echo "You are". $netname. "Netizen!<br>";
echo "<br> your message is:<br>". $newnote. " <br> ";
echo "</font>";
}
}
}
}
?>

Function prototype: array explode (string separator,string input);

The explode function is widely used, and its main function is to split the specified string into a set delimiter and return it as an array. It is often used in the split file name to determine the file type, cutting user email and other occasions.

Explode processing instance of PHP string partition function

1, get the file name extension

$fileName = "Leaps Tutorial oulcn.jpg";
$str = Explode (".", $fileName);
Print_r ($STR);

We know that in the php file upload function, the most basic way to judge whether the file name is legitimate is to determine whether the extension is legitimate, this time you need to use the PHP string function explode to the file name segmentation process. In the above code, explode the function to split the file name into a delimiter. Enter the results as follows

Array ([0] => LEAPSOULCN [1] => jpg)

2, get the user email domain name information

$emailInfo = Explode ("@", $email);


Manual

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.

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.