PHP common functions and Frequently asked Questions _php tutorial

Source: Internet
Author: User
Tags parse error php web development strcmp strtok validation examples
First introduced the relatively simple but essential and practical knowledge, can be used as a manual query, suitable for the novice like me to see.

Introduction to PHP Common library functions

First, PHP string operation commonly used functions
1. Determine the length of the string
int strlen (String str)
2. Comparison of two strings
A. The strcmp function compares a binary security to two strings and is case-sensitive
int strcmp (string str1,string str2)
B. Comparing two strings in a case-insensitive manner
int strcasecmp (string str1,string str2)

3. Ask for two identical parts of the string
int strspn (string str1,string str2)
4. Ask for two different parts of a string
5.int strcspn (String str1,string str2)
6. Handling String case
A. Converting a string all to lowercase
String Strtolower (String str)
B. Converting a string all to uppercase
String Strtoupper (String str)
C. Capitalize the first character of a string
String Ucfirst (String str)
D. Converting the first character of each word in a string to uppercase
String Ucwords (String str)
7. Convert strings to HTML
A. Converting a newline character to an HTML termination tag
String bl2br (String str)
B. Converting special characters to wieldhtml equivalent form (non-parsing format)
String Htmlentities (String Str[,int quote_style[,int charset])
String Htmlspecialchars (String Str[,int quote_style[,string charset])
C. Converting HTML to plain text, removing all PHP and HTML tags
String Strip_tags (String str[,string allowable_tags])
D. Converting text to HTML equivalent form
Array get_html_translaction_table (int table[,int Quote_style])
E. Creating a custom conversion manifest
String Strtr (String Str,array replacements)
8. Alternative functions for regular expression functions
A. strtok function parses a string based on a predefined list of strings
String Strtok (String str,string tokens): Returns all content until the tokens is encountered
B. Parsing a string based on a predefined delimiter
Array explode (string separator,string str[,int limit]): Split string
C. Converting an array to a string
String implode (string delimiter, array array)
D. Find the first occurrence of a string
int Strpos (string str,string substr[,int offset])
E. Finding the last occurrence of a string
int Strrpos (string Str,char substr[,offset])
F. Replacing all instances of a string with another string
Mixed Str_replace (String occurrence,mixed replacement,mixed str[,int count])
G. Getting a portion of a string strstr returns the remainder of the first occurrence of a predefined string in a string
String Strstr (string str,string occurrence)
H. Returning part of a string based on a predefined offset
String substr (String str,int start[,ing length]): Start can be negative, indicating the beginning of the countdown
I. Determining how often a string appears
int Substr_count (string str,string substring)
J. Replacing a part of a string with another string
String Substr_replace (String str,string replacement,int start[,int length])
9. Populating and rejecting strings
A. Cropping a character starting from a string
String LTrim (String str[,string charliset])
B. Cropping a character from the end of a string
String RTrim (String str[,string charliset])
C. Clipping characters from both ends of a string
String Trim (String str[,string charliset])
D. Populating a string
String Str_pad (String Str,int length[,string pad_string[,int Pad_type])
10. Character and Word Count
A. Character count in a string
Mixed Count_chars (string Str[,mode])
B. Count the total number of words in a string
Mixed Str_word_count (string str[,int format])
Ii. Three forms validation functions commonly used in PHP Web development

(1) isset ();--suitable for detecting the presence of this parameter. To avoid referencing non-existent variables

Definition and scope: used to test whether a variable has a value (including 0,false, or an empty string returns true, but not null), that is: "http://localhost/?fo=" is also detectable and therefore not applicable. However, if the "http://localhost/" parameter does not contain the FO parameter, it can be detected with isset, at which point the isset ($_get[' fo ') returns false

Not applicable: This function is not suitable for validating the text in an HTML form in an efficient way. To check whether the user input text is valid, you can use empty ();

(2) empty ();--a function that is best used to check if a variable has a null value

Definition and scope: used to check if a variable has a null value: include: empty string, 0,null, or false, which return false, that is: "http://localhost/?fo=" or "http://localhost/?fo=0", The result of empty detection is ture

Not applicable: Not available for detection of 0 parameters

(3) Is_numeric ();--Check if the variable is a number

Definition and scope: Check if the variable is a number, only for the test number

Not applicable scope: But if the parameter name does not exist, it will be wrong, so it is not suitable for the first layer detection

Another useful validation function is Checkdate (Month,day, $year), which is used to confirm whether a date exists or whether it existed in the past.

Comprehensive Example:

Here is the form:
Copy the Code code as follows:




Form validation Examples




Pass valid value to pass NULL value to pass 0 value



Gender: Male: Female



Empty





[Code]
This is a validation
[Code] Ini_set ("Display_errors", 1);
Ini_set ("error_reporting", E_all); Print_r
Error_reporting (E_all);

$a =null;
if (Isset ($a)) echo ' variable $ A ' isset is true ';

Echo '

Isset of the situation:

';
if (Isset ($_get[' fo ')) {
echo ' variable \ ' fo\ ' isset is true, variable available ';
}else{
echo ' variable \ ' fo\ ' Isset is false, no variable set ';
}

Echo '

Empty case:

';
if (Empty ($_get[' fo '))) {
echo ' variable \ ' fo\ ' of empty is true, that is, null or invalid value ';
}else{
echo ' variable \ ' fo\ ' of empty is false, has value ';
}

Echo '

Is_numeric of the situation:

';
if (Is_numeric ($_get[' fo '))) {//There is no fo parameter in the parameter, there is an error.
echo ' variable \ ' fo\ ' Is_numeric is true, is the number ';
}else{
echo ' variable \ ' fo\ ' Is_numeric is false, not a number ';
}

echo "

\$_get[' fo ']= ' case:

";
if ($_get[' fo ']== ') {//There is no fo parameter in the parameter, then an error occurs.
echo ' fo no value, empty string ';
}elseif ($_get[' fo ']!= ') {
Echo ' fo has value, not for \ '. ';
}

echo "

\$_get[' sex ']= ' m ' Case:

";
if ($_get[' sex ']== ' m ') {//error occurs when there is no sex variable in the parameter.
Echo ' The man ';
}elseif ($_get[' sex ']== ' f ') {
echo ' female ';
}
?>

Third, other common library functions

(1) Ini_set ini_get--operable configuration parameter list
In order to make our program more compatible in different platforms, many times we have to get the current PHP operating environment parameters.
For example, we used to:
Gets the MAGIC_QUOTES_GPC state to determine whether we are escaping (addslashes) data when the form is submitted;
Set Max_execution_time to extend the execution time of the program;
Set error_reporting to make your project in the development and operation phase switch;
Set Memory_limit increase memory, etc...
(2) Ini_set (string varname, String newvalue)://Set parameters for the environment configuration
Ini_get (String varname)://Get Parameters for environment configuration
The PHP ini_set function is the value in the SET option, which takes effect after the function is executed, and when the script finishes, this setting also fails. Not all options can be changed by the function set. Specific values can be set, you can view the list in the manual
In fact, you put PHP ini_set function and ini_get combination so that, very good. For example, if you want to add your own file path to the config file, but you have no permission to change php.ini, you can combine 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, which is what the first page of the system defines for the Ui_handler function
(5) int intval (mixed var, int [base]);
This function converts a variable into an integer type. The parameter base that can be omitted is the base of the conversion, and the default value is 10. The converted variable var can be an array or any type variable other than the class.
(6) error_reporting (report_level) function--Set the error level of PHP and return to the current level
Where Report_level values are 0, 1, 2, 4, 8, 16, 、......、 4096, 8191
Example: Any number of the above options can be connected (with OR or |) using "or" to report all required levels of errors. For example, the following code turns off user-defined errors and warnings, performs certain actions, and then reverts to the original error level:
Copy CodeThe code is as follows:
disabling error Reporting

error_reporting (0);

Report Run-time errors

Error_reporting (E_error | e_warning | E_parse);

Report All Errors

Error_reporting (E_all);

?>
Common Troubleshooting Questions
1. Rand (Min,max) differs from Mt_rand (Min,max) if no optional parameter min and Max,mt_rand () are provided to return a pseudo-random number between 0 and Rand_max. For example, want a random number between 5 and 15 (including 5 and 15), with Mt_rand (5, 15).
Many of the old libc random number generators have some uncertainties and unknown characteristics and are slow. The rand () function of PHP uses the libc random number generator by default. The Mt_rand () function is informally used to replace it. The function uses the known characteristics of the Mersenne Twister as a random number generator, which can produce random values four times times faster than Rand () provided by LIBC.
2, PHP Echo, print, Print_r, printf, sprintf and Var_dump functions of the difference and use
1) Echo
Echo () is not actually a function, it is a PHP statement, so you do not need to use parentheses on it. However, if you want to pass more than one argument to Echo (), a parse error occurs when you use parentheses. and echo returns void and does not return a value, so it cannot be used to assign a value.
Example:
Copy CodeThe code is as follows: echo "55nav"; 55nav
Echo ("55nav"); 55nav
Echo ("55nav", "com"); An error occurred with parentheses that cannot pass multiple arguments
echo "55nav", "com", "is", "web"; You can separate multiple values with commas without parentheses, and output a 55nav COM is web
echo "55nav is good web."; The final display is for a row of 55nav is good web, regardless of whether the line is wrapped.
echo "$fistname com"; If $firstname = "55nav", 55nav com is output.
echo ' $firstname com '; Because the single quotation marks are used, the $firstname value is not output, but the output $firstname com12
?>
2) Print
Print () is the same as Echo (), but the echo speed is a little bit faster than print. It is not actually a function, so you do not need to use parentheses on it. However, if you want to pass more than one parameter to print (), a parse error occurs when you use parentheses. Note that print always returns 1, which is different from Echo, which means you can use print to assign a value, but it doesn't make sense.
Example:
Copy CodeThe code is as follows: echo $a; The value of $a is 14
?>;
3) Print_r Function--print the values of predefined variables
The Print_r function prints easy-to-understand information about variables.
Syntax: Mixed print_r (mixed $expression [, BOOL return])
If the variable is a string, the integer or float will output its value directly, and if the variable is an array, it will output a formatted array for readability, which is the format of the key and value. Similar for object objects. Print_r has two parameters, the first is a variable, the second can be set to true, and if set to True, returns a string, otherwise returns a Boolean value of true.
Example:
Copy CodeThe code is as follows:
$c = Print_r ($a);
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 parameters format is the converted format, starting with the percent sign ("%") to the end of the converted character. The following is the possible format value:
*%%– return percent symbol
*%b– binary number
*%c– characters in accordance with ASCII values
*%d– Signed decimal number
*%e– counting method (e.g. 1.5e+3)
*%u– unsigned decimal number
*%f– floating point (Local settings Aware)
*%f– floating point number (not local settings aware)
*%o– octal number
*%s– String
*%x– hexadecimal number (lowercase letter)
*%x– hexadecimal number (capital letter)
Arg1, arg2, arg++, etc. parameters will be inserted into the main string percent percent (%) Symbol. The function is executed incrementally, in the first% symbol, insert arg1, insert arg2 at the second% symbol, and so on. If the% symbol is more than the arg parameter, you must use a placeholder. After the placeholder is inserted in the% symbol, it consists of a number and a "\$". You can use numbers to specify the parameters that are displayed, see examples for details.
Example:
Copy CodeThe code is as follows: printf ("My name is%2\ $s%1\ $s", "55nav", "com"); Add 1\$ or 2\$ in front of s ..... Indicates the location of the following parameter display, this line shows my name is COM 55nav
?>
5) sprintf function
This function uses the same method as printf, except that the function writes the formatted string to a variable instead of the output.
Example:
Copy CodeThe code is as follows: $out = sprintf ("My name is%1\ $s%2\ $s", "55nav", "com");
Echo $out; Output My name is 55nav com
?>
6) Var_dump function
Function: The content, type, and length of the output variable's contents, type, or string. Commonly used to debug.
Example:
Copy CodeThe code is as follows: Var_dump ($a); Int (100)
$a = 100.356;
Var_dump ($a); Float (100.356)
?>

http://www.bkjia.com/PHPjc/736795.html www.bkjia.com true http://www.bkjia.com/PHPjc/736795.html techarticle first introduced the relatively simple but essential and practical knowledge, can be used as a manual query, suitable for the novice like me to see. PHP Common library function Introduction, PHP string operations commonly used 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.