Front-end learning of PHP string functions

Source: Internet
Author: User
Tags md5 digest md5 hash rtrim sprintf strcmp

The processing and parsing of strings is an important foundation in any programming language, and is often simple and important. The classification, parsing, storing and displaying of information, as well as the data in the network need to be done by manipulating strings. Especially in web development, most of the work of programmers is to manipulate strings, this article will detail the string functions in PHP

[note] about the properties and methods of strings in JavaScript.

Characteristics

Because PHP is a weakly typed language, other types of data can generally be applied directly to string manipulation functions and converted to string types for processing

echo substr ("1234567", 2, 4);  The string is processed using the function substr (), and the output substring is 345echo substr (123456, 2, 4);     The integer type is processed by string function, and the output is the same as strings 345echo hello;           Find the Hello constant first, you will see the common name as a string use

The string looks like an array, you can use the bracket syntax, but because you can't distinguish it from a real array, it brings two semantics, so it's best to use curly braces with the same function

$STR = "lamp";       echo $str. " <br> ";       echo $str {0};//output string $str first character Lecho $str [1];//output string $str second character a,[] Yes, but obsolete

When dealing with variable parsing, if you encounter a dollar sign in a string, the parser takes as much of the following words utilises as possible to make up a valid variable name, and if you want to explicitly specify the end of the name, enclose the variable name in curly braces.

    $lamp = Array (' OS ' = ' Linux ');      You can parse    echo "A OS is $lamp [OS].";        cannot be resolved, if you use quotation marks on an associative array, you must use curly braces, otherwise you will get an error    echo "A OS is $lamp [' OS '].";        Can be parsed, if you use quotation marks on an associative array, you must use curly braces, otherwise the    echo "A OS is {$lamp [' OS ']}.";        Can parse, note that PHP is the array subscript as a constant name, the constant does not exist when the constant name into a string, inefficient    echo "A OS is {$lamp [OS]}.";

[note] in PHP, a GB2312 encoded Chinese character accounts for 2 bytes, and a UTF-8 encoded kanji is 3 bytes

Output

Echo ()

void Echo (String $arg 1 [, String $ ...])

The Echo () function is used to output one or more strings, which will output all parameters without wrapping, with no return value.

Echo is not a function, so you don't have to use parentheses to indicate arguments, single quotes, double quotes. In addition, if you want to pass multiple arguments to echo, you cannot use parentheses

<?phpecho "Hello World", $foo = "Foobar"; echo "Foo is $foo"; Foo is Foobarecho $foo;          Foobar?>

Print ()

int print (string $arg)

The print () function is used to output a string and always returns 1

<?phpprint ("Hello World"), $foo = "Foobar";p rint "foo is $foo"; Foo is foobarprint $foo;          Foobar?>
Var_dump (Echo (' 123 '));//Error Var_dump (print (' 123 '));//int 1

Echo can accept multiple parameters (no parentheses), and print cannot

<?phpecho ' 1 ', ' 2 ', ' 3 ';//123print ' A ', ' B ', ' C ';//Error?>

Exit ()

The exit () function is used to output a message and exit the current script with no return value, and the function with the same name is Die ()

void exit ([string $status]) void exit (int $status)

If the status is a string, the function prints the status before exiting, and if the status is an integer, the value will be used as the exit status code and will not be printed out. The exit status code should be in the range 0 to 254 and should not use the exit status Code 255 reserved by PHP. Status code 0 is used to successfully abort the program

<?phpexit (' 0 ');//0exit (0);//no return value?>

Printf

The printf () function is used to output a formatted string

int printf (string $format [, Mixed $args [, mixed $ ...])

sprintf

The sprintf () function is used to write a formatted string into a variable

String sprintf (String $format [, Mixed $args [, mixed $ ...])

The string conversion format is as follows

    percent return percentage symbol%b    binary number%c    characters%d ASCII value notation    decimal number%e  scientific notation (e.g. 1.5e3)%u    unsigned decimal number%f or%f     floating-point numbers%o    octal number%s    string%x or%x  hexadecimal number
<?php$var = 10;printf ("%%,%b,%c,%d,%e,%u,%o,%f,%s,%x", $var, $var, $var, $var, $var, $var, $var, $var, $var, $var);//%, 1010,, 10,1.000000e+1,10,12,10.000000,10,a$result = sprintf ("%%,%b,%c,%d,%e,%u,%o,%f,%s,%x", $var, $var, $var, $var, $ var, $var, $var, $var, $var, $var); Var_dump ($result);//string '%,1010, 10,1.000000e+1,10,12,10.000000,10,a ' (length= ?>)

Space

Trim ()

The trim () function is used to remove whitespace characters (or other characters) from the beginning and end of a string, the filtered string

String Trim (String $str [, String $charlist = "\t\n\r\0\x0b"])

This function returns the result of the string str after removing the trailing whitespace characters. If you do not specify a second parameter, trim () will remove these characters:

"" (ASCII (0x20)), ordinary space character "\ T" (ASCII 9 (0x09)), tab "\ n" (ASCII (0x0A)), newline "\ R" (ASCII (0x0D)), carriage return "\" (ASCII 0 (0x0 0)), null byte character "\x0b" (ASCII One (0x0B)), Vertical tab

Charlist is an optional parameter, and the filter character can also be specified by the charlist parameter. Generally you want to list all the characters you want to filter, or you can use ".." To list a range of characters

LTrim ()

The LTrim function is used to delete white space characters (or other characters) at the beginning of a string

RTrim ()

The RTrim function is used to delete white space characters (or other characters) at the end of a string

<?php$text  = "   \t\thello world a1a1a1    "; $trimmed = Trim ($text); Var_dump ($trimmed);//string ' Hello World a1a1a1 ' (length=18) $trimmed = Trim ($text, "A1"); Var_dump ($trimmed);//string '        Hello World ' (length=13) $ Trimmed = Trim ($text, "1..e");//string '        Hello worl ' (length=12) var_dump ($trimmed); $ltrimmed = LTrim ($text); var_ Dump ($ltrimmed);//string ' Hello World a1a1a1    ' (length=22) $rtrimmed = RTrim ($text); Var_dump ($rtrimmed);//string '           Hello World a1a1a1 ' (length=23)?>

Str_pad ()

The Str_pad () function fills a string with another string for the specified length

String Str_pad (string $input, int $pad _length [, string $pad _string = "" [, int $pad _type = str_pad_right]])

The function returns the result of input being populated from the left, right, or both ends of the set length. If the optional pad_string parameter is not specified, input will be filled with a space character, otherwise it will be pad_string filled to the specified length

[note] If the value of pad_length is negative, less than or equal to the length of the input string, no padding will occur

<?php$input = "Alien"; Echo Str_pad ($input, 10); Output "Alien     " Echo str_pad ($input, ten, "-=", str_pad_left);//Output "-=-=-alien" Echo str_pad ($input, Ten, "_", Str_pad_bo TH); Output "__alien___" Echo Str_pad ($input, 6, "___");//Output "Alien_"?>

Uppercase and lowercase

Strtolower ()

strtolower-converting a string to lowercase

Strtoupper ()

strtoupper-converting a string to uppercase

Ucfirst ()

Ucfirst-converts the first letter of a string to uppercase

Ucwords ()

ucwords-converts the first letter of each word in a string to uppercase

<?php$foo = ' Hello world! '; Var_dump (Ucwords ($foo));//string ' Hello world! ' (length=12) Var_dump (Ucfirst ($foo));//string ' Hello world! ' (length=12) Var_dump (Strtoupper ($foo));//string ' HELLO world! ' (length=12) Var_dump (Strtolower ($foo));//string ' Hello world! ' (length=12)?>

Html

NL2BR ()

nl2br-inserting HTML wrap tags before all new lines in the string

String nl2br (String $string [, bool $is _xhtml = True])
<?php/*foo isn ' t<br/> bar */echo nl2br ("foo isn ' t\n bar");? >

Htmlspecialchars ()

String Htmlspecialchars (string $string [, int $flags = Ent_compat | ent_html401 [, String $encoding = Ini_get ("Default_charset") [, bool $double _encode = true]])

Htmlspecialchars-Converts the specified special symbol into an entity

& (Ampersand)            &amp; " (double quote)        &quot, unless Ent_noquotes is set ' (single quote)        & #039; or &apos;< (less than)            &lt;> (GRE Ater than)        &gt;
<?php$new = "<script>alert (1) </script>"; echo $new;//Eject 1$new = Htmlspecialchars ("<script>alert ( 1) </script> "); Echo $new; Display String "<script>alert (1) </script>"?>
<?php    $str = "<B>WebServer:</B> & ' Linux ' & ' Apache '";//string echo with HTML tags and single quotes often    Htmlspecialchars ($str, Ent_compat);//Convert HTML tags and convert double quotes to    echo "<br>\n";    Echo Htmlspecialchars ($str, ent_quotes);//Convert HTML tags and convert two quotation marks to    echo "<br>\n";    Echo Htmlspecialchars ($str, ent_noquotes);//Convert HTML tags and do not convert quotes?>

Htmlentities ()

String Htmlentities (string $string [, int $flags = Ent_compat | ent_html401 [, String $encoding = Ini_get ("Default_charset") [, bool $double _encode = true]])

Htmlentities-Converts all non-ASCII code to the corresponding entity code

The function of Htmlentities () and Htmlspecialchars () is to convert characters into HTML character encodings, especially URLs and code strings, to prevent character tokens from being executed by the browser. Htmlentities Convert all HTML tags, htmlspecialchars only format & ' "< and > these special symbols

<?php$str = "<p>123</p>"; echo $str;//Display paragraph 123echo htmlentities ($STR);//' 123 ' echo htmlspecialchars ($ STR);//' 123 '?>

Strip_tags ()

Strip_tags-attempts to return the given string str after removing null characters, HTML, and PHP markup results

String Strip_tags (String $str [, String $allowable _tags])

Use the optional second parameter allowable_tags to specify a list of characters that are not removed

<?php$text = ' <p>test paragraph.</p><!--Comment-to <a href= "#fragment" >other text</a > '; echo strip_tags ($text);//' Test paragraph. Other text ' echo ' \ n '; Echo strip_tags ($text, ' <p> '). ' <br> ';//<p>test paragraph.</p> other text$text = ' <div><b>123</b></div> '; echo Strip_tags ($text);//' 123 '?>

Addslashes ()

Addslashes-uses a backslash to refer to a string, which returns a string, which is preceded by a backslash for some characters, such as a database query statement. These characters are single quotes ('), double quotation marks ("), backslashes (\), and NUL (the NULL character)

String Addslashes (String $str)
<?php$str = "Is your name O ' Reilly?"; echo addslashes ($STR);//"Is your name o\ ' Reilly?"? >

Stripslashes ()

stripslashes-dereference A reference string

String Stripslashes (String $str)
<?php$str = "Is your name o\ ' Reilly?"; echo stripslashes ($STR);//"Is your name O ' Reilly?"? >

Formatting

Strrev ()

strrev-Inverse string

String Strrev (String $string)
<?phpecho Strrev ("Hello world!"); Output "!dlrow Olleh"?>

Strlen ()

strlen-Get string length

int strlen (String $string)
<?php$str = ' abcdef '; Echo strlen ($STR); 6$STR = ' ab CD '; echo strlen ($STR); 7?>

MD5 ()

md5-Calculating the MD5 hash value of a string

String MD5 (string $str [, bool $raw _output = false])

If the optional raw_output is set to True, then the MD5 Digest is returned in the original binary format of 16 bytes in length

<?php$str = ' Apple '; if (MD5 ($str) = = = ' 1f3870be274f6c49b3e31a0c6728957f ') {    echo ' would ' like a green ' or red app Le? ";}? >

Comparison

strcmp ()

strcmp-string comparison, if str1 is less than str2 returns < 0 if str1 is greater than str2 return > 0; if both are equal, return 0

int strcmp (String $str 1, String $str 2)
<?php$var1 = "Hello"; $var 2 = "Hello"; if (strcmp ($var 1, $var 2)!== 0) {    echo ' $var 1 is not equal to $var 2 in a case Sensitive string comparison ';}? >

STRNCMP ()

strncmp-string comparisons that limit string lengths

int strncmp (String $str 1, String $str 2, int $len)

If STR1 is less than str2 returns < 0, if STR1 is greater than str2 returns > 0, if both are equal, return 0

<?php echo strncmp ("XYBC", "a3234", 0); 0 echo strncmp ("XYBC", "a3234", 1); 1?>

STRCASECMP ()

strcasecmp-string comparison (case insensitive) if str1 is less than str2 returns < 0 if str1 is greater than str2 returns > 0; if both are equal, return 0

int strcasecmp (String $str 1, String $str 2)
<?php$var1 = "Hello"; $var 2 = "Hello"; if (strcasecmp ($var 1, $var 2) = = 0) {    echo ' $var 1 is equal to $var 2 in a case-i Nsensitive string comparison ';}? >

STRNATCMP ()

Strnatcmp-comparing strings using natural sorting algorithms

int strnatcmp (String $str 1, String $str 2)

If STR1 is less than str2 returns < 0, if STR1 is greater than str2 returns > 0, if both are equal, return 0

<?PHP$ARR1 = $arr 2 = Array ("Img12.png", "Img10.png", "Img2.png", "Img1.png"), Usort ($arr 1, "strcmp");p Rint_r ($arr 1) ;//array ([0] = img1.png [1] = img10.png [2] = img12.png [3] = = img2.png) Usort ($arr 2, "strnatcmp");//arra Y ([0] = img1.png [1] = img2.png [2] = img10.png [3] = img12.png) Print_r ($arr 2);? >

                                               Article from: http://www.cnblogs.com/xiaohuochai/p/6068883.html

Front-end learning of PHP string functions

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.