Common PHP functions and FAQs

Source: Internet
Author: User
Tags convert text to html php error php web development strtok

First, we will introduce some simple but essential and practical knowledge. It can be used as a manual query and is suitable for beginners like me.

Common PHP library functions

I. Common functions for PHP string operations
1. Determine the string length
Int strlen (string str)
2. Compare two strings
A. The strcmp function performs binary Security Comparison on two strings and is case sensitive.
Int strcmp (string str1, string str2)
B. Compare two strings in case-insensitive Mode
Int strcasecmp (string str1, string str2)

3. obtain the same part of the two strings.
Int strspn (string str1, string str2)
4. Find different parts of two strings
5. int strcspn (string str1, string str2)
6. process string case sensitivity
A. Convert all strings to lowercase letters.
String strtolower (string str)
B. Convert all strings into uppercase letters.
String strtoupper (string str)
C. Capital the first character of the string
String ucfirst (string str)
D. Convert the first character of each word in the string to uppercase.
String ucwords (string str)
7. Conversion between strings and HTML
A. convert a linefeed to an HTML termination mark
String bl2br (string str)
B. convert special characters into wieldHTML equivalent form (not parse format)
String htmlentities (string str [, int quote_style [, int charset])
String htmlspecialchars (string str [, int quote_style [, string charset])
C. convert HTML to plain text and remove all php and html tags.
String strip_tags (string str [, string allowable_tags])
D. convert text to HTML equivalent form
Array get_html_translaction_table (int table [, int quote_style])
E. Create a custom conversion list
String strtr (string str, array replacements)
8. Replacement functions of Regular Expression Functions
A. the strtok function parses strings Based on the predefined string list.
String strtok (string str, string tokens): returns all contents until the tokens are met.
B. Analyze strings based on predefined delimiters
Array explode (string separator, string str [, int limit]): Split string
C. Convert the array to a string
String implode (string delimiter, array)
D. Find the first occurrence of the string
Int strpos (string str, string substr [, int offset])
E. Find the last occurrence of the string
Int strrpos (string str, char substr [, offset])
F. replace all instances of the string with another string
Mixed str_replace (string occurrence, mixed replacement, mixed str [, int count])
G. Obtain a part of the string strstr and return the rest of the pre-defined string that begins to appear for the first time.
String strstr (string str, string occurrence)
H. return part of the string based on the predefined offset.
String substr (string str, int start [, ing length]): start can be a negative number, indicating the start of the last few
I. Determine the occurrence frequency of the string
Int substr_count (string str, string substring)
J. replace a part of a string with another string
String substr_replace (string str, string replacement, int start [, int length])
9. Fill and remove strings
A. Crop characters starting from the string
String ltrim (string str [, string charliset])
B. Crop characters from the end of a string
String rtrim (string str [, string charliset])
C. Crop characters from both ends of the string
String trim (string str [, string charliset])
D. Fill in the string
String str_pad (string str, int length [, string pad_string [, int pad_type])
10. Character and word count
A. String Character Count
Mixed count_chars (string str [, mode])
B. Total number of words in the string
Mixed str_word_count (string str [, int format])
2. Three form verification functions commonly used in PHP Web Development

(1) isset (); -- suitable for detecting whether this parameter exists. Used to prevent reference of non-existent Variables

Definition and scope of action: used to test whether a variable has a value (including 0, FALSE, or whether an empty string returns true, but cannot be NULL), that is, "http: // localhost /? Fo = "can also pass detection, so it is not applicable. However, if the "http: // localhost/" parameter does not include the fo parameter, you can use isset for detection. At this time, isset ($ _ GET ['fo']) returns false.

Not applicable: this function is not suitable for verifying text in html forms. To check whether the user input text is valid, you can use empty ();

(2) empty (); -- the best function to check whether a variable has a null value

Definition and scope of action: used to check whether a variable has a null value, including: null String, 0, null, or false. All of these return false, that is, "http: // localhost /? Fo = "or" http: // localhost /? When fo = 0 ", empty detects that all results are true.

Inapplicable scope: Not Applicable to parameters with a value of 0.

(3) is_numeric (); -- check whether the variable is a number

Definition and scope of action: Check whether the variable is a number. It is only applicable to the detection of numbers.

Not applicable scope: however, if the parameter name does not exist, an error occurs. Therefore, it is not suitable for the first-level detection.

Another useful verification function is checkdate (month, day, $ year) to check whether a Date exists or exists in the past.

Comprehensive example:

This is the form:
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312"/>
<Title> Form Verification example </title>
</Head>
<Body>
</Body>
<P>
<A href = "? Fo = Jack "> pass valid values </a> <a href = "? Fo = "> pass null values </a> <a href = "? Fo = 0 "> 0 </a>
<Br/>
<A href = "? Sex = m "> Gender: male </a> <a href = "? Sex = f "> Gender: female </a>
<Br/>
<A href = "/"> clear </a>
<Br/>
<Input type = "text" value = "<? Php echo $ _ GET ['fo']! = ''? $ _ GET ['fo']: '';?> "Size =" 155 "/>
</P>
</Html> [code]
This is verification
[Code] <? Php
Ini_set ("display_errors", 1 );
// Ini_set ("error_reporting", E_ALL); print_r
Error_reporting (E_ALL );

$ A = NULL;
If (isset ($ a) echo 'isset of variable $ a' is true ';

Echo 'If (isset ($ _ GET ['fo']) {
Echo 'isset of variable \ 'fo \ 'is true and the variable is usable ';
} Else {
The isset of echo 'variable \ 'fo \ 'is false and has no variable settings ';
}

Echo 'If (empty ($ _ GET ['fo']) {
Echo 'empty of variable \ 'fo \ 'is true, that is, null or invalid value ';
} Else {
The empty of echo 'variable \ 'fo \ 'is false and has a value ';
}

Echo 'If (is_numeric ($ _ GET ['fo']) {// if the parameter does not contain the fo parameter, an error occurs.
The is_numeric of echo 'variable \ 'fo \ 'is true, a number ';
} Else {
Is_numeric of echo 'variable \ 'fo \ 'is false, not a number ';
}

Echo "

If ($ _ GET ['fo'] = '') {// if the parameter does not contain the fo parameter, an error occurs.
Echo 'fo no value, empty string ';
} Elseif ($ _ GET ['fo']! = ''){
Echo 'fo has a value, not \'\'.';
}

Echo "

If ($ _ GET ['sex '] = 'M') {// an error occurs when no sex variable exists in the parameter.
Echo 'mal ';
} Elseif ($ _ GET ['sex'] = 'F '){
Echo 'femal ';
}
?>
 

Iii. Other common library functions

(1) ini_set ini_get -- List of operable configuration parameters
In order to make your programs have better compatibility on different platforms, we often need to obtain the runtime environment parameters of the current Php.
For example, we often use the following:
Obtain the magic_quotes_gpc status to determine whether to escape (addslashes) data when the form is submitted;
Set max_execution_time to extend the execution time of the program;
Set error_reporting to switch the development and operation phases of your project;
Set memory_limit to increase memory and so on...
(2) ini_set (string varname, string newvalue): // sets the environment configuration parameters.
Ini_get (string varname): // gets the environment configuration parameters
The PHP ini_set function is the value in the setting option. It takes effect after the function is executed and expires when the script ends. Not all options can be changed to function settings. You can set specific values to view the list in the manual.
In fact, if you combine the PHP ini_set function with ini_get, it is very good. For example, if you want to add your own include file path in the configuration file, but you have the permission to change php. ini, you can combine the following two functions:
Ini_set ('include _ path', ini_get ('include _ path'). ':/your_include_dir :');
(3) chdir (dirname (_ FILE _); // switch to the directory where global. php is located.
(4) ob_start ('ui _ handler '); // set the output buffer handle to ui_handler, that is, the content defined by the ui_handler function on the home page of the system.
(5) int intval (mixed var, int [base]);
This function converts a variable to an integer. The base parameter that can be omitted is the basis for conversion. The default value is 10. The converted variable var can be any type variable outside the array or class.
(6) error_reporting (report_level) function -- sets the PHP error level and returns the current level.
The value of report_level is 0, 1, 2, 4, 8, 16, 32 ,...... , 4096, 8191
Example: any number of the above options can be connected with "OR" (OR |), so that all the required levels of errors can be reported. For example, the following code disables User-Defined errors and warnings, performs some operations, and then restores to the original error level:
Copy codeThe Code is as follows: <? Php

// Disable Error Reporting

Error_reporting (0 );

// Report running errors

Error_reporting (E_ERROR | E_WARNING | E_PARSE );

// Report all errors

Error_reporting (E_ALL );

?>
FAQs
1. The difference between rand (min, max) and mt_rand (min, max). If the optional parameters min and max are not provided, the pseudo-random number between 0 and RAND_MAX is returned. For example, if you want a random number between 5 and 15 (including 5 and 15), use mt_rand (5, 15 ).
Many old libc random number generators have some uncertain and unknown features and are very slow. The rand () function of PHP uses the libc random number generator by default. The mt_rand () function is informal to replace it. This function uses known features in Mersenne Twister as a random number generator, which can generate random values at an average speed four times faster than the rand () provided by libc.
2. Differences between PHP echo, print, print_r, printf, sprintf and var_dump functions and their usage
1) echo
Echo () is actually not a function, it is a php statement, so you do not need to use parentheses for it. However, if you want to pass more than one parameter to echo (), a parsing error occurs when brackets are used. Besides, echo returns void and does not return values. Therefore, it cannot be used to assign values.
Example:
Copy codeThe Code is as follows: <? Php $ a = echo ("55nav"); // error! Cannot be used for value assignment
Echo "55nav"; // 55nav
Echo ("55nav"); // 55nav
Echo ("55nav", "com"); // an error occurred. Multiple parameters cannot be passed in parentheses.
Echo "55nav", "com", "is", "web"; // when no parentheses are needed, multiple values can be separated by commas, and 55nav com is web
Echo "55nav is good web."; // no matter whether or not a line feed is displayed, the final display is a line of 55nav is good web.
Echo "$ fistname com"; // If $ firstname = "55nav", 55nav com is output.
Echo '$ firstname com'; // because single quotes are used, the value of $ firstname is not output, but $ firstname com12 is output.
?>
2) print
Print () is the same as echo (), but the echo speed is a little faster than print. In fact, it is not a function, so you do not need to use parentheses for it. However, if you want to pass more than one parameter to print (), a parsing error occurs when brackets are used. Note that print always returns 1, which is different from echo, that is, print can be used to assign values, but it is not actually meaningful.
Example:
Copy codeThe Code is as follows: <? Php $ a = print ("55nav"); // This is allowed
Echo $ a; // the value of $ a is 14.
?>;
3) print_r function -- print the value of the predefined variable
The print_r function prints easy-to-understand information about variables.
Syntax: mixed print_r (mixed $ expression [, bool return])
If the variable is string, integer or float, its value is directly output. If the variable is an array, a formatted array is output for ease of reading, that is, the format corresponding to the key and value. Object objects are similar. Print_r has two parameters. The first parameter is a variable, and the second parameter can be set to true. If it is set to true, a string is returned. Otherwise, a Boolean value is returned.
Example:
Copy codeThe Code is as follows:
<? Php $ a = "55nav ";
$ C = print_r ($ );
Echo $ c; // the value of $ c is TRUE.
$ C = print_r ($ a, ture );
Echo $ c; // the value of $ c is the string 55nav.
?>
4) printf function
The printf function returns a formatted string.
Syntax: printf (format, arg1, arg2, arg ++)
The format parameter is the conversion format. It starts with the percent sign ("%") and ends with the conversion character. The following are possible format values:
* %-Percentage sign returned
* % B-binary number
* % C-ASCII characters
* % D-Signed decimal number
* % E-resumable counting (for example, 1.5e + 3)
* % U-Unsigned decimal number
* % F-floating point number (local settings aware)
* % F-floating point number (not local settings aware)
* % O-octal values
* % S-string
* % X-hexadecimal (lowercase letter)
* % X-hexadecimal number (uppercase letters)
Parameters such as arg1, arg2, arg ++ are inserted to the percent sign (%) in the main string. This function is executed step by step. In the first % symbol, insert arg1, at the second % symbol, insert arg2, and so on. If the % symbol is greater than the arg parameter, you must use a placeholder. After the placeholder is inserted with the % symbol, it consists of numbers and "\ $. You can use numbers to specify the displayed parameters. For more information, see the example.
Example:
Copy codeThe Code is as follows: <? Php printf ("My name is % s. "," 55nav "," com "); // My name is 55nav com
Printf ("My name is % 2 \ $ s % 1 \ $ s", "55nav", "com "); // Add 1 \ $ or 2 \ $ ..... the location where the following parameters are displayed. My name is com 55nav is displayed in this line.
?>
5) sprintf Function
This function is used in the same way as printf. The only difference is that the function writes formatted strings to a variable instead of output.
Example:
Copy codeThe Code is as follows: <? Php sprintf ("My name is % 1 \ $ s % 1 \ $ s", "55nav", "com"); // You will find nothing to output
$ Out = sprintf ("My name is % 1 \ $ s % 2 \ $ s", "55nav", "com ");
Echo $ out; // output My name is 55nav com
?>
6) var_dump Function
Function: outputs the content, type, and length of the variable, type, or string. It is often used for debugging.
Example:
Copy codeThe Code is as follows: <? Php $ a = 100;
Var_dump ($ a); // int (100)
$ A = 100.356;
Var_dump ($ a); // float (100.356)
?>

 

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.