Hướng dẫn like string in php

A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. See details of the string type.

Note: On 32-bit builds, a string can be as large as up to 2GB [2147483647 bytes maximum]

Syntax

A string literal can be specified in four different ways:

  • single quoted
  • double quoted
  • heredoc syntax
  • nowdoc syntax

Single quoted

The simplest way to specify a string is to enclose it in single quotes [the character '].

To specify a literal single quote, escape it with a backslash [\]. To specify a literal backslash, double it [\\]. All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning.

Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

Double quoted

If the string is enclosed in double-quotes ["], PHP will interpret the following escape sequences for special characters:

Escaped charactersSequenceMeaning
\n linefeed [LF or 0x0A [10] in ASCII]
\r carriage return [CR or 0x0D [13] in ASCII]
\t horizontal tab [HT or 0x09 [9] in ASCII]
\v vertical tab [VT or 0x0B [11] in ASCII]
\e escape [ESC or 0x1B [27] in ASCII]
\f form feed [FF or 0x0C [12] in ASCII]
\\ backslash
\$ dollar sign
\" double-quote
\[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation, which silently overflows to fit in a byte [e.g. "\400" === "\000"]
\x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation
\u{[0-9A-Fa-f]+} the sequence of characters matching the regular expression is a Unicode codepoint, which will be output to the string as that codepoint's UTF-8 representation

As in single quoted strings, escaping any other character will result in the backslash being printed too.

The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

Heredoc

A third way to delimit strings is the heredoc syntax:

The opening Heredoc identifier may optionally be enclosed in double quotes:

Example #11 Using double quotes in Heredoc

Nowdoc

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML construct, in that it declares a block of text which is not for parsing.

A nowdoc is identified with the same

The above example will output:

My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41

Example #14 Static data example

Variable parsing

When a string is specified in double quotes or with heredoc, variables are parsed within it.

There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.

The complex syntax can be recognised by the curly braces surrounding the expression.

Simple syntax

If a dollar sign [$] is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.

The above example will output:

He drank some apple juice.
He drank some juice made of .
He drank some juice made of apples.

Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket []] marks the end of the index. The same rules apply to object properties as to simple variables.

Example #15 Simple syntax example

The above example will output:

The character at index -2 is n.
Changing the character at index -3 to o gives strong.

For anything more complex, you should use the complex syntax.

Complex [curly] syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. The expression is written the same way as it would appear outside the string, and then wrapped in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

String offsets have to either be integers or integer-like strings, otherwise a warning will be thrown.

Example #18 Example of Illegal String Offsets

The above example will output:

string[1] "b"
bool[true]

Warning: Illegal string offset '1.0' in /tmp/t.php on line 7
string[1] "b"
bool[false]

Warning: Illegal string offset 'x' in /tmp/t.php on line 9
string[1] "a"
bool[false]
string[1] "b"
bool[false]

Note:

Accessing variables of other types [not including arrays or objects implementing the appropriate interfaces] using [] or {} silently returns null.

Note:

Characters within string literals can be accessed using [] or {}.

Note:

Accessing characters within string literals using the {} syntax has been deprecated in PHP 7.4. This has been removed in PHP 8.0.

Converting to string

A value can be converted to a string using the [string] cast or the strval[] function. String conversion is automatically done in the scope of an expression where a string is needed. This happens when using the echo or print functions, or when a variable is compared to a string. The sections on Types and Type Juggling will make the following clearer. See also the settype[] function.

A bool true value is converted to the string "1". bool false is converted to "" [the empty string]. This allows conversion back and forth between bool and string values.

An int or float is converted to a string representing the number textually [including the exponent part for floats]. Floating point numbers can be converted using exponential notation [4.1E+6].

Note:

As of PHP 8.0.0, the decimal point character is always .. Prior to PHP 8.0.0, the decimal point character is defined in the script's locale [category LC_NUMERIC]. See the setlocale[] function.

Arrays are always converted to the string "Array"; because of this, echo and print can not by themselves show the contents of an array. To view a single element, use a construction such as echo $arr['foo']. See below for tips on viewing the entire contents.

In order to convert objects to string, the magic method __toString must be used.

Resources are always converted to strings with the structure "Resource id #1", where 1 is the resource number assigned to the resource by PHP at runtime. While the exact structure of this string should not be relied on and is subject to change, it will always be unique for a given resource within the lifetime of a script being executed [ie a Web request or CLI process] and won't be reused. To get a resource's type, use the get_resource_type[] function.

null is always converted to an empty string.

As stated above, directly converting an array, object, or resource to a string does not provide any useful information about the value beyond its type. See the functions print_r[] and var_dump[] for more effective means of inspecting the contents of these types.

Most PHP values can also be converted to strings for permanent storage. This method is called serialization, and is performed by the serialize[] function.

Details of the String Type

The string in PHP is implemented as an array of bytes and an integer indicating the length of the buffer. It has no information about how those bytes translate to characters, leaving that task to the programmer. There are no limitations on the values the string can be composed of; in particular, bytes with value 0 [“NUL bytes”] are allowed anywhere in the string [however, a few functions, said in this manual not to be “binary safe”, may hand off the strings to libraries that ignore data after a NUL byte.]

This nature of the string type explains why there is no separate “byte” type in PHP – strings take this role. Functions that return no textual data – for instance, arbitrary data read from a network socket – will still return strings.

Given that PHP does not dictate a specific encoding for strings, one might wonder how string literals are encoded. For instance, is the string "á" equivalent to "\xE1" [ISO-8859-1], "\xC3\xA1" [UTF-8, C form], "\x61\xCC\x81" [UTF-8, D form] or any other possible representation? The answer is that string will be encoded in whatever fashion it is encoded in the script file. Thus, if the script is written in ISO-8859-1, the string will be encoded in ISO-8859-1 and so on. However, this does not apply if Zend Multibyte is enabled; in that case, the script may be written in an arbitrary encoding [which is explicitly declared or is detected] and then converted to a certain internal encoding, which is then the encoding that will be used for the string literals. Note that there are some constraints on the encoding of the script [or on the internal encoding, should Zend Multibyte be enabled] – this almost always means that this encoding should be a compatible superset of ASCII, such as UTF-8 or ISO-8859-1. Note, however, that state-dependent encodings where the same byte values can be used in initial and non-initial shift states may be problematic.

Of course, in order to be useful, functions that operate on text may have to make some assumptions about how the string is encoded. Unfortunately, there is much variation on this matter throughout PHP’s functions:

  • Some functions assume that the string is encoded in some [any] single-byte encoding, but they do not need to interpret those bytes as specific characters. This is case of, for instance, substr[], strpos[], strlen[] or strcmp[]. Another way to think of these functions is that operate on memory buffers, i.e., they work with bytes and byte offsets.
  • Other functions are passed the encoding of the string, possibly they also assume a default if no such information is given. This is the case of htmlentities[] and the majority of the functions in the mbstring extension.
  • Others use the current locale [see setlocale[]], but operate byte-by-byte. This is the case of strcasecmp[], strtoupper[] and ucfirst[]. This means they can be used only with single-byte encodings, as long as the encoding is matched by the locale. For instance strtoupper["á"] may return "Á" if the locale is correctly set and á is encoded with a single byte. If it is encoded in UTF-8, the correct result will not be returned and the resulting string may or may not be returned corrupted, depending on the current locale.
  • Finally, they may just assume the string is using a specific encoding, usually UTF-8. This is the case of most functions in the intl extension and in the PCRE extension [in the last case, only when the u modifier is used]. Although this is due to their special purpose, the function utf8_decode[] assumes a UTF-8 encoding and the function utf8_encode[] assumes an ISO-8859-1 encoding.

Ultimately, this means writing correct programs using Unicode depends on carefully avoiding functions that will not work and that most likely will corrupt the data and using instead the functions that do behave correctly, generally from the intl and mbstring extensions. However, using functions that can handle Unicode encodings is just the beginning. No matter the functions the language provides, it is essential to know the Unicode specification. For instance, a program that assumes there is only uppercase and lowercase is making a wrong assumption.

John

5 years ago

I've been a PHP programmer for a decade, and I've always been using the "single-quoted literal" and "period-concatenation" method of string creation. But I wanted to answer the performance question once and for all, using sufficient numbers of iterations and a modern PHP version. For my test, I used:

php -v
PHP 7.0.12 [cli] [built: Oct 14 2016 09:56:59] [ NTS ]
Copyright [c] 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright [c] 1998-2016 Zend Technologies

------ Results: -------

* 100 million iterations:

$outstr = 'literal' . $n . $data . $int . $data . $float . $n;
63608ms [34.7% slower]

$outstr = "literal$n$data$int$data$float$n";
47218ms [fastest]

$outstr =

This does not:



Without semicolon, it works fine:

garbage at iglou dot eu

6 years ago

You can use string like array of char [like C]

$a = "String array test";

var_dump[$a];
// Return string[17] "String array test"

var_dump[$a[0]];
// Return string[1] "S"

// -- With array cast --
var_dump[[array] $a];
// Return array[1] { [0]=> string[17] "String array test"}

var_dump[[array] $a[0]];
// Return string[17] "S"

- Norihiori

Ray.Paseur sometimes uses Gmail

3 years ago

md5['240610708'] == md5['QNKCDZO']

This comparison is true because both md5[] hashes start '0e' so PHP type juggling understands these strings to be scientific notation.  By definition, zero raised to any power is zero.

vseokdog at gmail dot com

3 years ago

Don't forget about new E_WARNING and E_NOTICE errors from PHP 7.1.x: they have been introduced when invalid strings are coerced using operators expecting numbers [+ - * / ** % > | & ^] or their assignment equivalents. An E_NOTICE is emitted when the string begins with a numeric value but contains trailing non-numeric characters, and an E_WARNING is emitted when the string does not contain a numeric value.

Example:
$foo = 1 + "bob-1.3e3"; 
$foo = "10.2 pigs " + 1.0;
Will produce: Warning: A non-numeric value encountered

Read more: //www.php.net/manual/en/migration71.other-changes.php

og at gams dot at

15 years ago

easy transparent solution for using constants in the heredoc format:
DEFINE['TEST','TEST STRING'];

$const = get_defined_constants[];

echo
Will output "foo 1 bar 2".

However, you cannot do this for all values in your namespace.  Class constants and static properties/methods will not work because the complex syntax looks for the '$'.

This will output "foo {Test::one} bar".  Constants and static properties require you to break up the string.

steve at mrclay dot org

13 years ago

Simple function to create human-readably escaped double-quoted strings for use in source code or when debugging strings with newlines/tabs/etc.

Chủ Đề