PHP Programming: Exploring the mysteries of strings

Source: Internet
Author: User
Tags array definition include ini variables php programming valid
Programming

In many web programming, strings are always generated and processed in large quantities. The proper use and processing of strings is also increasingly important for PHP programmers. This article from the simplest string definition has led you to the high-level string processing techniques, hope to be helpful to everyone.

  
A. Quote definition string

In PHP, a string is usually defined in a pair of quotes, such as:

' I am a string in single quotes '
"I am a string in double quotes"

The PHP parser uses a pair of quotes to judge a string. Therefore, all strings must use the same single or double quotation marks to define the start and end. For example, the following definition of a string is not valid:

"I am not a valid string since I have unmatching quote marks '"
' Me neither! '

When you define a string, only one quotation mark is treated as a definition character, either single or double quotes. So, if a string starts with double quotes, then only double quotes are parsed by the parser. This way, you can include any other character, even single quotes, in the double quote string. The following quotation marks are valid:

$s = "I am a ' single quote string ' inside a double quote string";
$s = ' I am ' a ' double quote string ' inside a single quote string ';

When PHP encounters the quotation marks that correspond to the beginning of the string, it is considered to be at the end of the string, so:

"Why doesn ' t" this "work?"

is actually divided into three parts by the PHP parser:

"Why doesn ' t"--a double quote string containing a single quote
this--extra characters, the analyzer cannot handle "work?"--normal string

The above example attempts to include double quotes in a double quote string, and the parser thinks the string is over when it encounters the second double quotation mark. To achieve the purpose of including quotes, it is necessary for the parser to ignore its intent when it encounters a string of ordinary quotes, and we add a backslash to the front of the quotation mark to tell PHP that the quotation mark is part of the string, and the correct representation is this:

"Why doesn ' t" that\ "work?"

A common problem in the English string is the use of apostrophes because it is a single quotation mark and is very common in English strings (all lattices). You have to be careful with these characters:

' You\ ' d better escape your apostrophes '

You can see that the backslash has a special meaning in the string, and when we need to include the backslash itself in the string, we need to
The symbol is preceded by an extra backslash. For example:

$file = "C:\Windows\System.ini";
Echo $file; Print Result: C:windowssystem.ini
$file = "C:\\windows\\system.ini";
Echo $file; Print Result: C:\Windows\System.ini

Another way to define a string is to eliminate the annoyance of special characters and to make it easier to refer to longer text. The string definition method begins with a <<< symbol immediately following a custom string, the last line ends with the custom string, and must be below.


Second, the string connection

Strings can be used with string connectors (.) To connect, such as:

$first_name = ' Charlie ';
$last_name = ' Brown ';
$full_name = $first_name. ' ' . $last_name;

A common use is to create large chunks of HTML string code, and the assignment number (=) connector (.) can be combined by shorthand (. =) notation, such as:

$html = ' <table> ';
$html. = ' <tr><td>number</td><td>square</td></tr> ';
for ($i=0; $i<10; $i++) {
$square = $i * $i;
$html. = ' <tr><td> '. $i. ' </td><td> '. $square. ' </td></tr> ';
}
$html. = ' </table> ';


Iii. using variables in strings

This feature allows you to stick to a lot of simple strings without using a connection symbol. PHP allows us to include string variables directly in a double quote string, and we can see that the following two strings have the same processing results.

$full_name = $first_name. ' ' . $last_name;
$full_name = "$first_name $last_name";

Single quote strings and double quote strings are handled differently in PHP. The contents of a double quote string can be interpreted and replaced, and the contents of a single quote string are always considered normal characters. For example:

$foo = 2;
echo "Foo is $foo"; Printed Result: Foo is 2
Echo ' foo is $foo '; Printed result: Foo is $foo
echo "Foo is $foo\n"; Printed Result: Foo is 2 (newline at the same time)
Echo ' foo is $foo\n '; Printed result: Foo is $foo\n

As you can see, even the backslash in the single quote string loses his extended meaning (except inserting a backslash \ and inserting single quotes \). So, you should use double quotes when you want to make variable substitutions in a string and include the escape sequences of \ n (line breaks). Single quote strings can be used anywhere else, and the use of single quote strings in a script is faster because the PHP parser handles single quote strings in a simpler way, and double quotes are more complex because they need to be parsed inside the string, so the processing speed is slightly slower.

When you refer to a complex combination of variables in a string, some problems may arise and the following code works correctly:

echo "value = $foo";
echo "value = $a[$i]";

The following code does not get the result we want:

echo "value = $a[$i][$j]"; We want to print an element of the two-dimensional array $a.

To avoid potential problems with these strings, we usually separate complex variables from strings, like this:

echo ' value = '. $A[$I][$J];

Another option is to enclose complex variables in curly braces, and the parser can correctly identify:

echo "value = {$a[$i][$j]}"//print an element of a two-dimensional array $a

In this way, there are new problems. When we want to refer to the curly braces character itself in a string, remember to use the escape character:

$var = 3;
echo "value = {$var}"; Print result "value = 3"
echo "value = \{$var}"; Print Result "value = {3}"


Three, slash and SQL statements

Generating HTML code or SQL query statements is often an interesting thing to do when writing PHP programs. Why, because it involves generating another type of code, you have to carefully consider and follow the writing syntax and rules required by this code.

Let's take a look at an example where you want to query a user whose name is "O ' Keefe" in the database, usually in the form of a SQL statement:

SELECT * from users where last_name = ' o\ ' Keefe '

Note that all the cells in the SQL statement (apostrophes) need to be escaped with a backslash. PHP specifically provides functions to handle situations where the function addslashes ($STR) is used to automatically insert a backslash escape character into a string in a quote character:

$last_name = "O ' Keefe";
$sql = "SELECT * from users where last_name = '". Addslashes ($last_name). "'";

In this example, you would also enclose a single quotation mark outside the last_name string (SQL syntax requirements), and because it uses a double quote string, you do not need to use an escape for this single quotation mark. The following statement is the equivalent of using a single quote string:

$sql = ' SELECT * from users where last_name = \ '. Addslashes ($last_name). '\'';

Any time you want to write a string in a database, you have to make sure that the quotes inside it correctly use the escape symbol, which is a common mistake many PHP beginners make.


Four, double quotes and HTML

Unlike SQL statements, double quotes are often used to represent strings in standard HTML languages (now many browsers have strong fault tolerance, allowing single quotes or even quotes to be used in HTML), such as:

$html = ' <a href= '. $url. ' " > '. $link. ' </a> ';
$html = "<a href=\" $url\ ">$link</a>";

The HTML language does not support backslash escaping, which is hidden when we use the form's inputs to transmit data. The best way to set the value of hidden inputs is to use the Htmlspecialchars () function to encode it. The following statement can normally transmit a data that might contain double quotes:

<input type=hidden name=var value= "<?php Echo htmlspecialchars ($var)?>" >



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.