PHP built-in function instance tutorial

Source: Internet
Author: User
Tags glob

Case-sensitive conversion functions

Strtolower ()
Strtoupper ()
Ucfirst ()
Ucword ()

Text HTML Tag processing function

Nl2br ()
Htmllentities ()
Htmlspecialchars ()
Stripslashes ()
Strip_tags ()
Number_format ()
Strrev ()
MD5 ()

<? PHP
// Convert to lowercase
$ A = 'www .jb51.net ';
Echo strtolower ($ );
// Result: www.jb51.net

// Convert to uppercase
$ A = 'www .jb51.net ';
Echo strtoupper ($ );
// Result: www.jb51.net

// Uppercase letters
$ A = 'www .jb51.net ';
Echo ucfirst ($ );
// Result: www.jb51.net

// Uppercase letters of each word
$ A = 'I love you ';
Echo ucword ($ );
// Result: I love you

/*
Tip: we all know the case sensitivity. Do you think the case sensitivity is different from the case sensitivity and the Case sensitivity?
In Windows, PHP is not case sensitive, but cannot be case insensitive in Linux.
For example
When the class is automatically loaded
<? PHP
Function _ autoload ($ classname ){
Include strtolower ($ classname). '. Class. php ';
}
$ OBJ = new myclass;
In this way, myclass. Class. php will be loaded.
Because the file name is often lowercase, it must be converted to lowercase.
?>
*/

// Nl2br converts spaces into entities <br/> because the line breaks are generally displayed in the browser. <br/> for example, the line breaks must be converted in the form message book. Otherwise, the lines cannot be converted. all tasks contain spaces.
$ A ='
I
Love
You
';
Echo $;
Echo nl2br ($ );
Result 1: I love you.
Result 2:
I
Love
You

// If you do not perform HTML Tag processing for form submission, the style or JS Code will be displayed and run directly.
/*
<Form>
<Input type = 'text' name = 'title'>
<Input type = 'submit 'name = 'submit 'value = 'Submit'>
</Form>

When you enter
<H1> www.jb51.net A large font is displayed upon submission.
But you wanted
<H1> www.jb51.net So proceed
When you enter <SCRIPT> alert ('www .jb51.net') </SCRIPT>
Javascript will be run once submitted
If this is not the case, you have to deal with it to prevent hackers from finding the entrance to your attack.
The default form submission method is get.
*/
// When you enter <div> Echo htmlspecialchars ($ _ Get ['title']); // filtered
Result: <div> When you view the source code, you will know that <and> have been replaced with <>. The page prototype is displayed.
Another important thing is that, if you do not deal with <div> some of the articles that have been copied have their own tag styles, your page layout may be disrupted and CSS conflicts may occur.
Htmllentities () function user and htmlspecialchars () are not used in the opposite way.

The strip_tags () function can be used when you need to keep the tag.
Echo strip_tags ($ _ Get ['title'], '<B> <p> <strong> If you view the source code, you will find that <div> no more

/*
Add the input I love 'jb51 ';
The submission result is I love \ 'jb51 \ '. The backslash is escaped.
What should I do if I want to output the original text?
You can use this PHP function stripslashes ()
Cancel escape
Echo stripslashes ($ _ Get ['title']);
The result is I love 'jb51 ';
What if HTML tags are contained?
<A href = "http://www.jb51.net/"> I love 'jb51 '</a>
What should I do with prototype output? I can combine two functions to use what I have already said.
Echo htmlspecialchars (stripslashes ($ _ Get ['title']);
Results: <a href = "http://www.jb51.net/"> I love 'jb51' </a>
*/

// Number_format () This function is used to format the currency function. Different countries have different habits, so the display of the required currency is different. For example, the Chinese money in the mall is usually in this format.
Use commas (,) to retain the number of decimal places'
This function is easy to use.
Number_format ($ money, which indicates the number of decimal points reserved. 'What are the decimal points separated 'And 'What are the decimal points separated ')
$ Price = '1970. 100 ';
Echo number_format ($ money, 2 ,',','.');
Result: 123.465.789, 23
Echo number_format ($ money, 2, '.', ','); // Chinese
Result: 123,465,789.23

// Strrev () returns the string
$ STR = 'HTTP: // www.jb51.net ';
Echo strrev ($ Str );
Result: MOC. tenwii. www //: Ptth

// MD5 indicates that the user name and password must be encrypted to prevent hackers.
$ A = 'admin ';
Echo $ B = MD5 ($ );

Built-in functions are functions provided by PHP. Using these functions, You can implement many functions such as is_int, is_integer, and is_long to determine whether the variables are integer is_float, is_double, and is_real, determine whether the variable is floating-point is_bool determine whether the variable is Boolean is_string determine whether the variable is a string is_array determine whether the variable is an array type is_resource determine whether the variable is a resource type is_object determine whether the variable is an object is_null judge whether the variable is null ['script _ name'] returns/mantis/test. PHP, relative path;
_ File _ absolute path of the returned file D: \ projects \ mantis \ test. php
$ _ Server ['HTTP _ x_forwarded_proto ']
$ _ Server ['https']
$ _ Server ['server _ port']
$ _ Server ["request_uri"] URI is used to specify the page to be accessed.
$ Globals: A Global combination array containing all the variables. The variable name is the key of the array.
Explode splits another string using one string to return a string array.
Implode uses a character to link an array element to a string.
$ _ Server ['server _ name'] Host Name of the server where the current script is located
$ _ Server ['HTTP _ host'] Domain Name
$ _ Server ['server _ ADDR '] IP address of the server where the current script is located
Trim removes spaces at the beginning and end of a string.
Basename
Dirname returned directory
Krsort-Sort arrays in reverse order by key name
Set_time_limit () sets the maximum script execution time.

Time () returns the current UNIX timestamp.

Is_string () determines whether the variable is a string.

Is_bool

Is_inteter

Is_float

Strtotime -- parses the date and time descriptions of any English text into UNIX timestamps

File_exists check that the file or directory does not exist

Fopen () Open the specified file or URL

Feof () determines whether the file pointer is at the end

Fgets () reads a row from the object pointer

Trim () removes spaces before and after a row

Strlen () returns the length of the string.

Str_replace
Isset
Str_replace ("\ 0", '', $ t_self) replace \ 0 in t_self with""
Strpos-find the first position in the string
$ _ Server ['server _ soft'] Server Information
Realpath returns the normalized absolute path name.
Directory_separator
In Linux, path_separator is a ":" number, and a ";" number on Windows.
Set_include_path: Set incldue_path

Get_include_path: Get the current include_path

Count () returns the length of the array. If the value is not an array, 1 is returned.

Substr (string, int start [int length]) returns the string of the length starting from the specified position of start.
$ _ Server ['local _ ADDR '] iis7 is used to obtain the Server IP Address
$ _ Server ['remote _ ADDR '] IP address of the browser user
Array_pad-fill the array with a value to the specified length
Memory_get_usage () returns the amount of memory allocated to PhP.
Spl_autoload_register registers the _ autoload () function
Ob_get_contents () return the contents of the output buffer
Strtolower () converts uppercase letters to lowercase letters
Extension_loaded ('zlib ') to check whether the extension is loaded.
Ini_get returns the configuration item value in PHP. ini.
Ini_set: set the value of the configuration item in PHP. ini, ini_set ("memory_limit", '256m'); takes effect only during script execution, and script execution completes resetting the value
Php_eol PHP line terminator

Preg_replace: replace a regular expression.

Preg_match (string pattern, string subject [, array matches [, int flags]) -- Regular Expression matching

Htmlspecialchars convert special characters to HTML entities
Ceil () returns an integer
Floor () Rounding
The round () Rounding Method is very useful for 10 uncommon PHP built-in functions

1. sys_getloadavg ()

Sys_getloadavt () can obtain the system load. This function returns an array containing three elements, each representing the average load of the system in the past 1, 5, and 15 minutes.

Instead of letting the server go down due to excessive load, it is better to take the initiative to die a script when the system load is very high. sys_getloadavg () is used to help you implement this function. But unfortunately, this function is invalid in windows.


2. Pack ()

Pack () can convert a 32-bit hexadecimal string returned by MD5 () to a 16-bit binary string, saving storage space.


3. cal_days_in_month ()

Cal_days_in_month () returns the total number of days in a specified month.


4 ._()

WordPress developers often see this function as well as _ E (). These two functions have the same functions and can be used in combination with the gettext () function to implement multilingual website operations. For more information, see the relevant section of the PHP manual.


5. get_browser ()

Before sending the page, check what your browser can do? Get_browser () can obtain the browser type and functions supported by the browser. However, you need a php_browscap.ini file to provide a reference file for the function.

Note that this function is based on the general features of the browser. For example, if the user closes the browser's support for Javascript, the function cannot know this. However, this function is very accurate in determining the browser type and OS platform.

6. debug_print_backtrace ()

This is a function used for debugging and can help you find logical errors in the code. To understand this function, let's look at an example:

  • <? PHP
  • $ A = 0;
  • Function iterate (){
  • Global $;
  • If ($ A <10)
  • Recur ();
  • Echo $ A. ",";
  • }
  • Function recur (){
  • Global $;
  • $ A ++;
  • // How did I get here?
  • Echo "\ n ";
  • Debug_print_backtrace ();
  • If ($ A <10)
  • Iterate ();
  • }
  • Iterate ();
  • ?>
Output:
#0 recur () called at [c: \ htdocs \ php_stuff \ index. php: 8]
#1 iterate () called at [c: \ htdocs \ php_stuff \ index. php: 25]
#0 recur () called at [c: \ htdocs \ php_stuff \ index. php: 8]
#1 iterate () called at [c: \ htdocs \ php_stuff \ index. php: 21]
#2 recur () called at [c: \ htdocs \ php_stuff \ index. php: 8]
#3 iterate () called at [c: \ htdocs \ php_stuff \ index. php: 25]
#0 recur () called at [c: \ htdocs \ php_stuff \ index. php: 8]
#1 iterate () called at [c: \ htdocs \ php_stuff \ index. php: 21]
#2 recur () called at [c: \ htdocs \ php_stuff \ index. php: 8]
#3 iterate () called at [c: \ htdocs \ php_stuff \ index. php: 21]
#4 recur () called at [c: \ htdocs \ php_stuff \ index. php: 8]
#5 iterate () called at [c: \ htdocs \ php_stuff \ index. php: 25]
 

7. metaphone ()

This function returns the metaphone value of a word. words with the same pronunciation have the same metaphone value. That is to say, this function can help you determine whether the two words have the same pronunciation. However, it is invalid for Chinese characters.

8. natsort ()

Natsort () can sort an array by natural sorting. Let's look at an example:

  • <? PHP
  • $ Items = array ("100 apples", "5 apples", "110 apples", "55 apples ");
  • // Normal sorting:
  • Sort ($ items );
  • Print_r ($ items );
  • ?>
Outputs:
# Array
#(
# [0] = & gt; 100 apples
# [1] = & gt; 110 apples
# [2] => 5 apples
# [3] => 55 apples
#)
Natsort ($ items );
Print_r ($ items );
# Outputs:
# Array
#(
# [2] => 5 apples
# [3] => 55 apples
# [0] = & gt; 100 apples
# [1] = & gt; 110 apples
#)

 

9. levenshtein ()

Levenshtein () tells you the "distance" between two words ". It tells you how many letters need to be inserted, replaced, and deleted if you want to change one word to another. Let's look at an example:

  • <? PHP
  • $ Dictionary = array ("php", "JavaScript", "CSS ");
  • $ Word = "japhp ";
  • $ Best_match = $ dictionary [0];
  • $ Match_value = levenshtein ($ dictionary [0], $ word );
  • Foreach ($ dictionary as $ W ){
  • $ Value = levenshtein ($ word, $ W );
  • If ($ value <$ match_value ){
  • $ Best_match = $ W;
  • $ Match_value = $ value;
  • }
  • }
  • Echo "did you mean the '$ best_match' category ?";
  • ?>

 

10. glob ()

Glob () Makes You Think It is silly to use opendir (), readdir () and closedir () to find files.

  • <? PHP
  • Foreach (glob ("*. php") as $ file ){
  • Echo "$ file \ n ";
  • }
  • ?>
For more details, see Baidu encyclopedia http://wenku.baidu.com/view/02c23a2e7375a417866f8ffd.html.

 

Related Article

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.