PHP most detailed from getting started to mastering (iv) strings in--php

Source: Internet
Author: User
Tags array length explode rtrim sha1 sha1 encryption sprintf strcmp

PHP from Beginner to proficient

The string in PHP

Hello everyone, continue to follow up the most detailed knowledge of PHP update, this week, with you to focus on the use of strings in PHP. In PHP, strings are a very important concept, basically you think of the string processing function, the system has been related functions. PHP Since its inception, is for the web development, Web site development, string processing, is a big highlight of PHP.

The following bloggers will give you a detailed introduction to the commonly used strings in PHP:

Three ways to declare a string

1, "": the variable "{$a}" can be parsed in double quotation marks, any escape character can be used in double quotation marks;
2, ': Cannot parse variable in single quotation mark, cannot use escape character in single quotation mark (but can use single quotation mark itself and escape character itself--->\ ' \ \);
3. Delimiter:<<< identifier
The identifier must be shelf written, and the entire line cannot have other characters
You can use a variable in the delimiter, you can use a character, or you can use a single double quote

Examples show:

Echo <<<str
This is the delimiter \ n
The declared string \ n
Q's front-end world \ n
Str

various output functions

1, Echo: outputs the content directly. The
① can be a function usage echo () or an instruction usage echo "";
② instruction usage can print multiple parameters, separated by commas, echo "", "", "";
function usage can only print one parameter; Echo ("");

2, Print: basically similar to the Echo function, but
① always has a return value of 1;
② can only pass one parameter, no matter how the function is written or the instruction is written;

3, Print_r: When you print arrays and objects, the matching of keys and values is displayed in a certain format; When the
Print_r prints an array, the pointer to the array is moved to the last edge. Use Reset () to get the pointer back to the beginning. (Not recommended!) Recommended var_dump)

4, Var_dump: Commissioning dedicated!! Displays information such as the type of printing, value, and so on, when the array object is printed, the display key value matching is indented;

5, exit () and Die (): Two functions full alias relationship, no difference!! The
outputs information and ends the current script (it can not output information).
Exit, Exit (), Exit ("") are valid;

6, printf: Print the content, and format the variable output;
The first parameter: the string content that needs to be printed, with multiple placeholders;
Second to many parameters: the variable corresponding to the placeholder one by one,
function: The following variables, according to the format requirements of the placeholder output;
percent sign
%b binary
%c character
%d signed decimal number according to ASCII value
%e The sustainable counting method (such as 1.5e3)
%u unsigned decimal number
%f or%f floating-point numbers
floating-point numbers retain 6 decimal places (rounded) by default, and numbers between% and F can be inserted to indicate precision. A fractional part of a number that represents a number of decimals, rounded, or integer that represents the exact total width (integer + decimal + total digits of the decimal point), and if the width < actual width is set, the setting is not valid if the width > actual width is set, and the left space is the complement.
0 requires a 0 before the width of the% (0 only);
%o octal
%s string
%x or%x hexadecimal number
7, sprintf: As with printf, just not the output statement, but the converted result is assigned to a variable;
Eg: $str =sprintf ("%.2f", 1,23456) retains two decimal places, assigned to STR;

Examples show:

$num = 10;
echo "123", "456", "789";
Print ("123");
printf ("Haha%bha", $num);

Common functions for PHP strings

Trim (): Removes spaces at both ends of the string;
LTrim (): Remove the space to the left of the string;
RTrim (): Delete the space to the right of the string;

You can pass in the second argument to delete the relevant characters on both sides;
Echo Trim ($STR, "! ");--> as long as the string appears on both sides! and spaces are deleted.
Principle: Starting from both sides of the string, looking inward to find the characters in the second parameter, as soon as the discovery is deleted, until the first character that does not appear is encountered!!

The second parameter is often written as: "\t\n\r\0\x0b", which is used to delete spaces and related symbols;

"" (ASCII (0x20)), plain space.
? "\ T" (ASCII 9 (0x09)), tab.
? "\ n" (ASCII (0x0A)), line break.
? "\ R" (ASCII (0x0D)), carriage return.
? "\" (ASCII 0 (0x00)), null byte character.
? "\x0b" (ASCII One (0x0B)), Vertical tab.

Examples show:

$str = "This is a space! ";
Echo LTrim ($STR). " \ n ";
echo RTrim ($STR). " \ n ";
Echo Trim ($STR, "! ")." \ n ";
Echo Trim ($STR, "! lattice"). " \ n ";
Echo Trim ($str, "\t\n\r\0\x0b"). " \ n ";

Str_pad (): Fills the string with the specified character, to the specified length;
① the string to be populated;
② how long the string needs to be populated. Must be selected.
If the length <= input string, it does not work;
③ text that needs to be filled; optional;
The default space padding.
④ on which side of the string is populated: Str_pad_left/str_pad_right/str_pad_both (2,0,1);
The default is padding on the right. If you choose both, fill it out from both sides.

Examples show:

$str= "ABCDE"; Echo Str_pad ($str, one, "123", Str_pad_both);

Strtolower (): Turns all letters into lowercase;
Strtoupper (): Turns all letters into uppercase;
The above two are often used for case-insensitive comparisons!

Ucfirst (): Turns the first letter of the string into uppercase;
Ucwords (): Turns the first letter of each word into uppercase (a space-delimited word);

The latter two are only responsible for the first letter, regardless of the case of the other letters. If you only need to capitalize the first letter, always match strtolower () to lowercase all letters first.

Examples show:

$str= "Hello MY world"; Echo Ucwords (strtolower($str));

HTML-related functions

1. NL2BR ($STR): Converts all newline characters in the string to </br>.
2. Htmlspecialchars ($string): Converts the specified HTML symbol to the entity content (not the execution);
&:&amp; " :&quot;
':& #039; <:&lt;
>:&gt; Space:&nbsp;
After turning into a special character, the browser automatically resolves to the corresponding tag symbol without having to turn back.

Examples show:

Echo <<<str
This is the delimiter \ n
The declared string \ n
Q's front-end world \ n
Str
echo nl2br ($STR);

Htmlspecialchars ($STR);

3, Strip_tags ($STR) Delete the HTML tag that appears, delete all the HTML tags in the string
Parameters: 1. String of HTML tags that need to be filtered
2. Permitted HTML tags, such as strip_tags ($str, "<b>"), allow only B tags to exist in $str;

Examples show:

$str = <<<str    "hahaha"\ n    "hee hee"\ n    str        ; Echo NL2BR ($str);     Echo Htmlspecialchars ($_post["Test"]);     Echo "&lt;&gt;" ;   <?= "haha"    ?>  //  output expression, cannot be used in PHP, usually used for HTML nesting: 

Strrev ($STR): Reverses the string "123"--"321"

Strlen ($STR): counts the number of characters in a string, Chinese = 3 characters
Mb_strlen ($STR): Measure the length of a multibyte string, either in English or Chinese, as a length
{Many string lengths in PHP are prefixed with mb_, specifically for manipulating Chinese multibyte strings}

Number_format (): Formats a floating-point number into a string
Parameters: 1. Floating-point numbers that need to be formatted (required)
2. Keep several decimals, not reserved by default
3. Display symbol for decimal point, default.;
4. The display symbol of the thousand separator, default,;


MD5 ()/SHA1 (): Encrypt the string using MD5 and SHA1 encryption algorithm respectively;

Examples show:

1 $str = "ABCDEFG"; 2 Echo Strrev ($str); 3 4 $str = "ABCDEFG"; 5 Echo strlen ($str);

comparison of strings

1. You can compare by operator
① if both sides are characters, the ASCII value of the first letter is compared;
② If one side is a number, then the string is converted to a number and then compared;

2, strcmp ($str 1, $str 2)
① $str 1> $str 2---1 $str 1< $str 2------1 $str 1== $str 2----0

②STRNCMP is exactly the same as strcmp, just a third parameter that is required to represent the length of the string

3, strcaseccmp case-insensitive to full-string

4, strnatcmp the string according to the natural sorting algorithm to compare
strcmp ("10", "2"), 1<2 return-1 according to ASCII code
STRNATCMP ("10", "2"); According to natural order, 10>2 returns 1
So two functions return 0 when the strings are equal, without any difference

Similar_text ($first, $second) returns the similarity of two strings.

Examples show:

Var_dump (Similar_text ("Img12", "Img13"));

Separation of strings

Explode the first delimiter (cannot be Empty ""), the second string to be processed, the third one divides the string up to several, if it is less than the actual score, the first N-1 is normal, the last one contains all characters;

Preg_split A string separated by an expression, the argument is the same, the first argument is a regular expression;


Parameter: ① the string to be split;
② a number of characters to do an element of the array, optional, default one;
③ separates each character of the string into arrays;
Implode (string connectors, array arrays) links the array to a string with the specified connector;
Eg:implode ("", ["a", "B", "C"])---->ABC
Implode (",", ["a", "B", "C"])---->a,b,c

Examples show:

Var_dump (explode(",", "S,t,r,i,n,g", 3)); Var_dump (str_split("Hahahahaa", 3));

substr (String $string, Int $start)
① the string to intercept, required
② starting from the first few characters, must be selected
③ intercept length is optional, the default is directly intercepted to the last (Chinese characters equivalent to three characters, with MB_SUBSTR);
Mb_substr ($str, $start) is used to intercept Chinese strings, one character in Chinese
Var_dump (substr ("1234561111", 8,5));


Finds strstr in a string finds and returns whether a substring is contained in the string and returns False if not found
① the string to be searched for, required
② need to find the substring, required
③true/false false: Returns all strings after the substring and substring, default
True: Returns the part before the substring

Stristr function Ibid., Case insensitive

STRRCHR takes the position of the last occurrence of the first substring of the first string, and returns the current position and subsequent strings;
① characters to be searched
② the character that needs to be looked up, if the second argument is a string, then only the first character of the string is used, and if found, returns the position of the last occurrence of the character, the next part;

Examples show:

Var_dump (Strstr ("123456", 3));
Var_dump (STRRCHR ("123456", "234"));

Focus!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Strpos returns the position of a substring in a string, first occurrence
① the string to be searched for
② the string to find
③ from the beginning of the first, the default from the beginning

Strrpos returns a substring in the string, the last occurrence of the position, the other ibid.
Stripos is not case-sensitive and returns the position of the first occurrence;
The Strripos is not case-sensitive and returns the last occurrence of the position;

Examples show:

1 Var_dump (strpos("123456aaxaa", "AA"));

Str_replace
① the replaced part, which can be a string or an array
② new content, which can be a string or an array
③ Original String

Case ① First string, second string
Var_dump (Str_replace ("E", "/", "Aajsnianceomoe555el"));
E in the original string is replaced by/
Case ② First array, second array
>>>1. Two array length equal, replace each
2. Array one length > array two length, the first array remaining with "" replaced (deleted)
3. Array one length < array two length, second array left unused
The case ③ the first array, the second string, and each of the arrays, replaced with a string.

Examples show:

1 Var_dump (str_replace("E", "/", "Aajsnianceomoe555el")); 2 Var_dump (str_replace(["E", "0"], ["/", ""], "Aajsnianceomoe5550el"));

We are here to share this issue and we'll see you next time. Feel good content of small partners please point of recommendation, Welcome to comment below comment area and Bo master interaction, thank you!

Not finished, to be continued ...

For more exciting content, stay tuned for Q's front-end World Tech blog.

PHP most detailed from getting started to mastering (iv) strings in--php

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.