PHP string functions

Source: Internet
Author: User
Tags md5 hash

PHP string functions
* Directory [1] features [2] Output [3] space [4] case sensitive [5] HTML [6] format [7] compared to the previous

String processing and analysis are an important foundation in any programming language and are often simple and important. The classification, parsing, storage, and display of information, as well as the data in the network, must be completed by operating strings. This is especially important in web development. Programmers mostly work on operating strings. This article will detail the string functions in php.

[Note] here are the attributes and methods of strings in javascript.

 

Features

Because php is a weak type language, other types of data can be directly applied to string operation functions, and converted to string type for processing.

Echo substr ("1234567", 2, 4); // process the string using the substr () function and output the substring 345 echo substr (123456, 2, 4 ); // use the string function to process the integer type, and the output is also the string 345 echo hello; // If the constant is not found, the constant name is considered as a string.

The string looks like an array and can use the brackets syntax. However, because it cannot be distinguished from the real array, it is recommended to use curly brackets with the same functions.

$ Str = "lamp"; echo $ str. "<br>"; echo $ str {0}; // the first character lecho $ str [1] In the output string $ str; // The second character a and [] in the output string $ str can also be used, but it is out of date.

When processing variable parsing, if you encounter a dollar sign in the string, the parser will retrieve as many characters as possible to form a valid variable name. If you want to explicitly specify the end of the name, enclose variable names with curly brackets

$ Lamp = array ('OS' => 'linux '); // You can parse echo "A OS is $ lamp [OS]. "; // It cannot be parsed. Brackets must be used if the subscript of the associated array is enclosed in quotation marks. Otherwise, an error occurs in echo" a OS is $ lamp ['OS']. "; // It can be parsed. Brackets must be used if the subscript of the associated array is enclosed in quotation marks. Otherwise, an error occurs in echo" a OS is {$ lamp ['OS]}. "; // It can be parsed. Note that PHP regards the array subscript as the constant name. If the constant does not exist, the constant name is converted into A string, which is less efficient. echo" a OS is {$ lamp [OS]}. ";

[Note] in php, A GB2312 Encoded chinese character occupies 2 bytes, and a UTF-8 Encoded chinese character occupies 3 bytes

 

Output

Echo ()

void echo ( string $arg1 [, string $... ] )

The echo () function is used to output one or more strings. It outputs all parameters without line breaks and returns no values.

Echo is not a function. Therefore, you do not have to use parentheses to specify parameters. single quotation marks and double quotation marks are acceptable. Additionally, you cannot use parentheses if you want to pass multiple parameters to echo.

<?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 strings and always returns 1

<?phpprint("Hello World");$foo = "foobar";print "foo is $foo"; // foo is foobarprint $foo;          // foobar?>
Var_dump (echo ('123'); // returns the error var_dump (print ('123'); // int 1

Echo can accept multiple parameters (not parentheses), but print cannot.

<? Phpecho '1', '2', '3'; // 123 print 'A', 'B', 'C'; // error?>

Exit ()

The exit () function is used to output a message and exit the current script. No return value is returned. The function with the same name is die ()

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

If status is a string, the function prints status before exiting. If status is an integer, the value is used as the exit status code and will not be printed. The exit status code ranges from 0 to 254. The exit status code 255 retained by PHP should not be used. Status Code 0 is used to successfully stop the program

<? Phpexit ('0'); // 0 exit (0); // No return value?>

Printf

The printf () function is used to output formatted strings.

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

Sprintf

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

string sprintf ( string $format [, mixed $args [, mixed $... ]] )

The String Conversion format is as follows:

% Return percent sign % B Binary Number % c according to ASCII value character % d with symbol decimal number % e scientific notation (such as 1.5e3) % u unsigned decimal number % f or % F Floating Point Number % 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=44)?>

 

Space

Trim ()

The trim () function is used to remove spaces (or other characters) at the beginning and end of a string and filter the string.

string trim ( string $str [, string $charlist = " \t\n\r\0\x0B" ] )

This function returns the result after str removes the first and last spaces. If the second parameter is not specified, trim () removes these characters:

"" (ASCII 32 (0x20), common space character "\ t" (ASCII 9 (0x09 )), tab "\ n" (ASCII 10 (0x0A), line break "\ r" (ASCII 13 (0x0D )), carriage Return "\ 0" (ASCII 0 (0x00), Null Byte "\ x0B" (ASCII 11 (0x0B), vertical Tab

Charlist is an optional parameter, and the filter character can also be specified by the charlist parameter. You can use ".." to list all characters to be filtered.

Ltrim ()

The ltrim function is used to delete spaces (or other characters) starting with a string)

Rtrim ()

The rtrim function is used to delete white spaces (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 uses another string to fill the string with the specified length

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

This function returns the result after the input is filled to the specified length from the left, right, or both ends. If the optional pad_string parameter is not specified, the input will be filled with space characters; otherwise, it will be filled with the specified length by pad_string.

[Note] if the value of pad_length is negative and smaller than or equal to the length of the input string, no filling will occur.

<? Php $ input = "Alien"; echo str_pad ($ input, 10); // output "Alien" echo str_pad ($ input, 10, "-=", STR_PAD_LEFT ); // output "-=-Alien" echo str_pad ($ input, 10, "_", STR_PAD_BOTH ); // output "_ Alien ___" echo str_pad ($ input, 6, "___"); // output "Alien _"?>

 

Case sensitivity

Strtolower ()

Strtolower-converts a string to lowercase

Strtoupper ()

Strtoupper-converts 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-insert the HTML line feed mark before all new lines of 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 a specified special symbol to an object

& (ampersand)            &amp;" (double quote)        &quot;, unless ENT_NOQUOTES is set' (single quote)        &#039; or &apos;< (less than)            &lt;> (greater than)        &gt;
<? Php $ new = "<script> alert (1) </script>"; echo $ new; // pop up 1 $ new = htmlspecialchars ("<script> alert (1) </script> "); echo $ new; // display string" <script> alert (1) </script> "?>
<? Php $ str = "<B> WebServer: </B> & 'linux '& 'apache'"; // string echo htmlspecialchars ($ str, ENT_COMPAT); // convert the HTML Tag and double quotation mark echo "<br> \ n"; echo htmlspecialchars ($ str, ENT_QUOTES ); // convert the HTML Tag and the conversion quotation mark echo "<br> \ n"; echo htmlspecialchars ($ str, ENT_NOQUOTES); // convert the HTML Tag and the quotation mark?>

Htmlentities ()

string htmlentities ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = true ]]] )

Htmlentities-convert all non-ASCII codes into corresponding Entity Codes

The functions of htmlentities () and htmlspecialchars () are both HTML character encoding, especially url and code string, to prevent the Character Mark from being executed by the browser. Htmlentities converts all html tags. htmlspecialchars only formats the special symbols & '"<and>.

<? Php $ str = "<p> 123 </p>"; echo $ str; // Display Section 123 echo htmlentities ($ str ); // '20180101' echo htmlspecialchars ($ str); // '20180101'?>

Strip_tags ()

Strip_tags-returns the result of removing null characters, HTML, and PHP tags from the given string 'str '.

string strip_tags ( string $str [, string $allowable_tags ] )

Use the optional second allowable_tags parameter to specify the list of characters not to be removed

<?php$text = '<p>Test paragraph.</p><!-- Comment --> <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 reference a string and returns a string. This string must be prefixed with a backslash before certain characters for database query statements. These characters are single quotation marks ('), double quotation marks ("), backslash (\), and NUL (NULL)

string addslashes ( string $str )
<?php$str = "Is your name O'reilly?";echo addslashes($str);// "Is your name O\'reilly?"?>

Stripslashes ()

Stripslashes-references a reference string

string stripslashes ( string $str )
<?php$str = "Is your name O\'reilly?";echo stripslashes($str);//"Is your name O'reilly?"?>

 

Format

Strrev ()

Strrev-reverse string

string strrev ( string $string )
<? Phpecho strrev ("Hello world! "); // Output "! Dlrow olleH "?>

Strlen ()

Strlen-get the string length

int strlen ( string $string )
<?php$str = 'abcdef';echo strlen($str); // 6$str = ' ab cd ';echo strlen($str); // 7?>

Md5 ()

Md5-calculate the MD5 hash value of a string

string md5 ( string $str [, bool $raw_output = false ] )

If the optional raw_output is set to TRUE, the MD5 message digest is returned in the original 16-byte length binary format.

<?php$str = 'apple';if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {    echo "Would you like a green or red apple?";}?>

 

Comparison

Strcmp ()

Strcmp-string comparison. If str1 is less than str2, <0 is returned. If str1 is greater than str2,> 0 is returned. If the two are equal, 0 is returned.

int strcmp ( string $str1 , string $str2 )
<?php$var1 = "Hello";$var2 = "hello";if (strcmp($var1, $var2) !== 0) {    echo '$var1 is not equal to $var2 in a case sensitive string comparison';}?>

Strncmp ()

Strncmp-Comparison of strings with limited string lengths

int strncmp ( string $str1 , string $str2 , int $len )

Returns <0 if str1 is less than str2; returns> 0 if str1 is greater than str2; returns 0 if both are equal

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

Strcasecmp ()

Strcasecmp-string comparison (Case Insensitive). If str1 is smaller than str2, <0 is returned; If str1 is greater than str2,> 0 is returned; if the two are equal, 0 is returned.

int strcasecmp ( string $str1 , string $str2 )
<?php$var1 = "Hello";$var2 = "hello";if (strcasecmp($var1, $var2) == 0) {    echo '$var1 is equal to $var2 in a case-insensitive string comparison';}?>

Strnatcmp ()

Strnatcmp-use a natural Sorting Algorithm to compare strings

int strnatcmp ( string $str1 , string $str2 )

Returns <0 if str1 is less than str2; returns> 0 if str1 is greater than str2; returns 0 if both are equal

<?php$arr1 = $arr2 = array("img12.png", "img10.png", "img2.png", "img1.png");usort($arr1, "strcmp");print_r($arr1);//Array ( [0] => img1.png [1] => img10.png [2] => img12.png [3] => img2.png )usort($arr2, "strnatcmp");//Array ( [0] => img1.png [1] => img2.png [2] => img10.png [3] => img12.png )print_r($arr2);?>

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.