PHP Learning String

Source: Internet
Author: User
Tags rtrim strcmp string find
This article introduces the content of PHP learning in the string, now share to everyone, the need for friends can refer to

Create

PHP supports 4 ways to create a string: single quotes, double quotes, heredoc grammatical structure, and nowdoc grammatical structure.

1. Single quotation marks

In single-quote strings, variables and special characters are not replaced by escapes, except for backslashes and single quotes themselves:

Echo ' Arnold once said: "I\ ' ll be back" '; # Arnold once said: "I'll be Back" echo ' you deleted c:\\*.*? '; # you deleted c:\*.*?

2. Double quotes

Ability to recognize variables and escape sequences in a string:

$juice = ' Apple '; Echo ' $juice juice. '; # Apple Juice.echo "Hello \nworld!"; #Hello #world!

3. heredoc Grammatical structure

Similar to double-quoted strings. The end tag must be written in the head, cannot have indents and spaces, and there should be a semicolon at the end of the tag, and the variables between the tags can be parsed normally, but the function will not. Often used when the output contains a large number of HTML documents.

$str = ' Heredoc '; $html = <<<end<p class= "container" >    <p class= "Row" >        <p class= " Col-xs-4 ">            <p> $str </p>        </p>    </p></p>end;echo $html #<p class=" Container ">#    <p class=" Row ">#        <p class=" col-xs-4 "># <p>heredoc</p>#        </p>#    </p>#</p>

4. nowdoc Grammatical structure

heredocsimilar to the syntax structure string, but nowdoc does not perform parsing operations on variables and escape sequences.

$str = ' Nowdoc '; $html = <<< ' END ' <p class= "container" >    <p class= "Row" >        <p class= " Col-xs-4 ">            <p> $str </p>        </p>    </p></p>end;echo $str #<p class=" Container ">#    <p class=" Row ">#        <p class=" col-xs-4 ">#            <p> $str </p>#        < /p>#    </p>#</p>

String encoding

In PHP strings, each character is stored in one byte (in memory), which means that PHP can only support a 256 character set and therefore does not support Unicode.

The
string in PHP is implemented by a byte array plus an integer indicating the buffer length. There is no information on how to convert bytes into characters, as determined by the programmer. Since PHP does not specifically specify the encoding of the string, how exactly is the string encoded? The answer is that the string is encoded in the same way that the script file is encoded.

In general, although the Unicode character set is not supported in PHP, but the file supports UTF-8 encoding, most of the time there is no problem, but encountered the string encoding conversion when there is a problem, such as in a UTF-8 encoded PHP file, The number of characters (6) of the program output is not equal to the actual number of characters (2):

Echo strlen (' China '); # 6
mbstring provides functions for multibyte strings that can help you with multibyte encoding in PHP. In addition, mbstring can encode and convert the possible character encodings to each other.

Therefore, when you need to manipulate the Unicode character set string, be sure to install the mbstring extension and use the appropriate function instead of the native string function:

Echo Mb_strlen (' China ', ' UTF-8 '); # 2
mbstring Extensions Most of the functions need to be processed based on an encoding (internal code), be sure to use UTF-8 encoding uniformly, most of which can be in PHP. INI configuration.

For PHP string encoding issues, it is strongly recommended that:

    1. PHP script file using UTF-8 no BOM encoding format;

    2. String operations use mbstring extended functions;

    3. Database connection and storage using UTF-8 encoding;

    4. The HTML document uses UTF-8 encoding.

String formatting

1. String removal

rtrim()-Remove whitespace characters (or other characters) at the end of a string
ltrim()-Remove whitespace characters (or other characters) at the beginning of a string
trim()-Remove whitespace characters (or other characters) from the beginning and end of the string

$text = "\t\tthese is a few words:)  ... \ n "; Echo RTrim ($text); # "\t\tthese is a few words:) ..." echo ltrim ($text); # "These is a few words:)  ... \ n "echo trim ($text);  # "These is a few words:) ..." $trimmed = Trim ($hello, "LD"); # "Hello Wor"

2. Format the string for output

nl2br()-Insert HTML Wrap tags before all new lines in the string
printf()-Output formatted string
sprintf()-Write the formatted string to the variable

echo nl2br ("Hello \nworld"); #hello #worldprintf (' I need to pay $%.02LF ', 1.3568); # I need to pay $1.36$str = sprintf (' I need to pay $%.02lf ', 1.3568); Echo $str; # I need to pay $1.36

htmlspecialchars()-Convert special characters to HTML entities
htmlentities()-Converts a character to an HTML escape character

Echo htmlspecialchars ("<a href= ' test ' >Test</a>", ent_quotes); # &lt;a href=& #039;test& #039;&gt; Test&lt;/a&gt;echo htmlentities ("A ' quote ' is <b>bold</b>"); # A ' Quote ' is &LT;B&GT;BOLD&LT;/B&GT

3. Format the string to store

stripslashes()-Dereference a reference string
addslashes()-Use a backslash to reference a string

$str = "Is your name o\ ' Reilly?"; echo stripslashes ($STR); # is your name O ' Reilly?echo addslashes ($STR);   # is your name o\ ' Reilly?

4. Change the letter case of the string

strtolower()-Convert a string to lowercase
strtoupper()-Converts a string to uppercase
ucfirst()-Converts the first letter of a string to uppercase
ucwords()-Converts the first letter of each word in a string to uppercase

$str = "Mary had A Little Lamb and She loved It so"; Echo Strtolower ($STR); # Mary had a little lamb and she loved it Soecho Strtoupper ($STR); # MARY had A LITTLE LAMB and SHE loved IT so$foo = ' Hello world! '; $foo = Ucfirst ($foo); # Hello world! $foo = ucwords ($foo); # Hello world!

String joins and splits

1.explode()

Use one string to split another string:

$pizza  = "Piece1 piece2 piece3 piece4 piece5 piece6"; $pieces = Explode ("", $pizza);p Rint_r ($pieces); # Array ([0] = Piece1 [1] = Piece2 [2] = Piece3 [3] = Piece4 [4] = = Piece5 [5] = = Piece6)

2.implode() 或 join()

Stitching the values of a one-dimensional array into a string:

$array = Array (' LastName ', ' email ', ' phone '), Echo implode (', ', $array); # Lastname,email,phone

3.substr()

Returns a substring of a string:

echo substr (' abcdef ', 1);     # Bcdefecho substr (' abcdef ', 1, 3);  # Bcdecho substr (' abcdef ',-1, 1); # f

string comparison

1.strcmp()

Binary Secure string Comparisons (case-sensitive):

Echo strcmp (' Jochen ', ' Jochen '); # 32, if STR1 is less than str2 returns < 0, if STR1 is greater than str2 returns > 0, if both are equal, 0 is returned.

2.strcasecmp()

Binary security comparison string (case insensitive):

Echo strcasecmp (' Jochen ', ' Jochen '); # 0

3.strnatcmp()

Compare strings using the Natural sorting algorithm:

echo strnatcmp (' img12.png ', ' img10.png '); # 1,

String Find and Replace

1.strstr()

Finds the first occurrence of a string and returns a string:

echo strstr (' name@example.com ', ' @ '); # @example. com

2.strpos()

Where to find the first occurrence of a string:

$hello = ' Hello World ', if (Strpos ($hello, ' H ')!== false) {    echo ' find ';} else {    echo ' No find ';}

3.str_replace()

Match the string and replace it:

$search = "World"; $replace = "Shanghai"; $subject = "Hello world!"; Echo Str_replace ($search, $replace, $subject); # Hello Shanghai

4.substr_replace()

Replace the string at the specified location:

$replace = "Shanghai"; $subject = "Hello world!"; Echo Substr_replace ($subject, $replace, 6); # Hello Shanghai

Regular expressions

1.preg_match()

To perform a regular expression match:

$email = ' 10001110@qq.com '; $pattern = "/^ ([a-za-z0-9]) + ([. a-za-z0-9_-]) *@ ([. a-za-z0-9_-]) + ([. a-za-z0-9_-]+) + ([. a-za-z0-9_-]) $/"; if (Preg_match ($pattern, $email, $match)) {    echo ' matches success 

2.preg_match_all()

Perform a global regular expression match:

$str = "Name: <b>john poul</b> <br> Title: <b>php guru</b>";p reg_match_all ("/<b> (.  *) <\/b>/u ", $str, $result);p Rint_r ($result); # array ([0] = = Array ([0] = John Poul [1] = + PHP Guru) [1] = = Array ([0] = John Poul [1] = PHP Guru))

3.preg_split()

To delimit a string with a regular expression:

$keywords = Preg_split ("/[\s,]+/", "Hypertext language, Programming");p Rint_r ($keywords); # Array ([0] = hypertext [1 ] = language [2] = programming)

4.preg_replace()

Perform a search and replace of a regular expression:

$str = ' foo   o '; Echo preg_replace ('/\s\s+/', ' ', $str); # ' foo o ' $count = 0;echo preg_replace (Array ('/\d/', '/\s/'), ' * ', ' XP 4 to ',-1, $count); # Xp***toecho $count; # 3

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.