A string in PHP

Source: Internet
Author: User
PHPData types are divided into eight data types, PHPString is also one of them, today we will explain in detail PHPString.

Brief introduction

The implementation of a string in PHP is a byte array followed by an integer indicating the length of the buffer. There is no information on how to convert bytes into characters, which is determined by the programmer. There is no limit to what values a string consists of and, in particular, the byte with a value of 0 can be anywhere in the string.
Since PHP does not specifically specify the encoding of the string, how exactly is the string encoded? For example, is the string "á" exactly equal to "\xe1" (iso-8859-1), "\xc3\xa1" (utf-8,c form), "\x61\xcc\x81" (utf-8,d form) or any other possible expression? The answer is that the string is encoded in the same way that the script file is encoded.

The representation of a string

PHP strings can be represented in 4 ways, including:

Single quote/double quote/heredoc/nowdoc

All 4 of these methods support the writing of strings into multiple lines, while line breaks and spaces in the string are kept as-is in the characters, that is, in the source format. If you want to eliminate line breaks, you can write as a single line and use the string concatenation operator.


Single quotes are simple to use, with single quotes, only two escape characters, \ ' and \ \

If the string contains double quotation marks, the use of single quotation marks will be very concise.


Double quotes support more escape characters, such as \ n and \ T. In addition, the escape character supports octal notation, hexadecimal notation, and UTF-8 notation:

\[0-7]{1,3}

\x[0-9a-fa-f]{1,2}

\u{[0-9a-fa-f]+}


Similarly, in a string that is represented by double quotation marks, single quotes are not escaped.

Another important feature of the string represented by double quotation marks is the parsing of the middle variable in the string:

"Hi, $str."

Once the parser encounters the $ symbol, it gets the string between the $ symbol and the next character that is not an English letter, an Arabic numeral, or an underscore, and treats it as a variable name that is automatically ignored if the variable is not in the program.

If you want to output the $ symbol, you must use the escape character \$


Heredoc syntax

Syntax format:

<<<str

String content

Str


Note that the above STR is a custom identifier (you can add double quotes) for the start and end of the auxiliary flag string. In addition, <<<STR must be a newline character after.

The identifier that specifies the end of the string must be a different row and begin writing from the first column. This line must not contain any other characters except for a semicolon (;) that may be behind it. This means that the identifier cannot be indented, and the semicolon cannot have any blank or tab characters before or after it. More importantly, the end identifier must be preceded by a newline that is recognized by the local operating system, such as \ n in UNIX and Mac OS X systems, and an end delimiter (possibly followed by a semicolon) that must be followed by a newline.

The Heredoc syntax parses a variable in a string as if it were a double-quote notation.

Note that when Heredocs contains variable parsing, it cannot be used to initialize the properties of the class.


Nowdoc syntax

Syntax format:

<<< ' str '

String content

Str


The Nowdoc syntax is similar to the heredoc syntax, characterized by the need for identifiers to be surrounded by single quotes. And the Nowdoc syntax does not parse the variables in the string.

<?php    $name = "Pish";    echo <<< ' str1 '  My name is $name .<br>  str1;  ? >

Variable parsing in strings

The simplest way is to write the variable name directly, for example:

$name = ' Ann ';  $str = "Hello $name!";

In this way, you must have a character at the end of the variable name that cannot be used to name the variable, such as "!" in the previous example, unless, of course, the string has ended.


If the variable name is followed by a letter or a number, then the variable will not be parsed correctly, because once the parser encounters the $ symbol, it will get the string after the $ symbol until the next character that is not an English letter, an Arabic numeral, or an underscore, as the variable name, if there is no such variable in the program, is automatically ignored.

An exception is an array element, where an array element uses] to identify the end of a variable, so there can be other letters or numbers after.


If you want to better control the variable name or use a complex expression, you can use {} to assist the identity.

Attention:

1.$ and {must be close together, such as: ${or {$, or the curly braces will be parsed as a normal character in the string.

2. There must be a} symbol, otherwise an error occurs.

3. If the $ symbol is next to the variable name, there must be no spaces between them.

4. When parsing an array element, only the curly brace syntax can correctly parse the quoted key name

$str = "Hello ${name}";  $str = "Hello ${  name  }";  $str = "Hello {$name  }";  $str = "Hello {$  name  }";  Error

When you use only one layer of curly braces, you cannot handle the return value of a function or method or class constants and class static variables. The correct approach is to use two-ply curly braces:

{${getname ()}}            function  {${$object->getname ()}}   //Method  {${beers::softdrink}}//     class constant  {${beers:: $ale}}          // class variables

The following example shows the mutable variables in a string:

$name = ' Ann ';  $Ann = ' Jeck ';  echo "Hello {${$name}}"; Hello Jeck  echo "Hello ${$name}";   Hello Jeck    class Foo {    var $bar = ' I am bar ';  }  $foo = new Foo ();  $bar = ' bar ';  $baz = Array (' foo ', ' Bar ', ' baz ', ' Quux ');  echo "{$foo-$bar}\n";          I am Bar.  echo "{$foo->{$baz [1]}}\n];     I am Bar.

To access a string in the form of an array

A string can be accessed as a read-write array, when the key of the array is fixed to 0, 1, 2 ...

You can use square brackets or curly braces to access elements in a string:

$str = "ABCDEFG";  $str [0] = "2";  $str {1} = 3;  echo Var_dump ($STR);  String (7) "23CDEFG"

Note that an subscript write that exceeds the length of the string will lengthen the string and fill it with spaces. Bidding clubs are converted to integers under non-integer types. Illegal subscript types produce a e_notice level error. Writing a string with a negative subscript results in a e_notice level error, and an empty string is returned when the string is read with a negative subscript. Only the first character of the assignment string is used when writing. Assigning a value with an empty string assigns a value that is a NULL character.
The PHP string is internally an array of bytes. Therefore, it is not safe to use curly braces to access or modify strings to multibyte character sets. This type of operation should only be done for single-byte encodings such as iso-8859-1 strings.

Operator

The string supports these operators:

. .=

This operator is used to concatenate two strings:

$str 1 = "Hello". " World ";  $str 1. = "!";  echo $str 1;     Hello world!

String functions

strlen (str)

Returns the length of a string

$str 1 = "ABCDEFG";  $str 2 = "good everyone!";  Echo strlen ($str 1); 7  Echo strlen ($str 2);//10

The above is all the content of this article, hope can bring you a new understanding of the string Oh ~

Related recommendations:

The most complete PHP string handling function

PHP string converted to lowercase function strtolower ()

Several forgotten PHP string processing functions

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.