PHP common functions and common problems answer _php tips

Source: Internet
Author: User
Tags html form lowercase parse error php web development rand sprintf strcmp strtok

First of all introduce a relatively simple but essential and practical knowledge, can be used as a manual query, suitable for beginners like me to see.

Introduction to PHP Common library functions

PHP string operation of common functions
1. Determine string length
int strlen (String str)
2. Compare two strings
A. strcmp function compares 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. Find two strings of the same part
int strspn (string str1,string str2)
4. Find different parts of two strings
5.int strcspn (String str1,string str2)
6. Handling string Capitalization
A. Convert all strings to lowercase
String Strtolower (String str)
B. Convert a string to uppercase
String Strtoupper (String str)
C. Capitalize the first character of a string
String Ucfirst (String str)
D. Converts the first character of each word in a string to uppercase
String Ucwords (String str)
7. Strings and HTML convert to each other
A. Converting a newline character to an HTML termination tag
String bl2br (String str)
B. Converting special characters to wieldhtml equivalent (unresolved 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, remove 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. Create a custom conversion manifest
String Strtr (String Str,array replacements)
8. Alternate function of regular expression function
A. Strtok functions parse strings based on predefined string lists
String Strtok (String str,string tokens): Returns all content until tokens is encountered
B. Parsing strings according to predefined delimiters
Array explode (string separator,string str[,int limit]): Split string
C. Convert an array to a string
String implode (string delimiter, array array)
D. Finding 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. Replace all instances of a string with another string
Mixed Str_replace (String occurrence,mixed replacement,mixed str[,int count])
G. Getting part 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 predefined offsets
String substr (String str,int start[,ing length]): Start can be a negative number, representing the penultimate start
I. Determining the frequency of string occurrences
int Substr_count (string str,string substring)
J. Replace part of a string with another string
String Substr_replace (String str,string replacement,int start[,int length])
9. Padding and culling strings
A. Crop characters start from a 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 the ends of a string
String Trim (String str[,string charliset])
D. Filling strings
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 number of words in a string
Mixed Str_word_count (string str[,int format])
Two, PHP web development commonly used in three form validation functions

(1) isset ();--suitable for detecting the existence of this parameter. To avoid referencing a variable that does not exist

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

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

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

Definition and scope: used to check whether a variable has a null value: Includes: null string, 0,null, or FALSE, which returns false, that is, "http://localhost/?fo=" or "http://localhost/?fo=0", The results of empty detection are ture.

No scope: not suitable for detecting parameters that can be 0

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

Definition and scope: Check whether the variable is a number and only apply to the detection number

No scope: But if the parameter name does not exist, there will be an error, so it is not suitable for the first layer detection

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

Comprehensive Example:

This is the form:

Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 "/>
<title> Form Validation Example </title>
<body>
</body>
<p>
<a href= "? fo=jack" > Valid value </a> <a href= "? fo=" > Null value </a> <a href= "? fo=0" > 0 value </a>
<br/><br/>
<a href= "sex=m" > Sex: Male </a> <a href= "sex=f" > Gender: Female </a>
<br/><br/>
<a href= "/" > Empty </a>
<br/><br/>
<input type= "text" value= "<?php echo $_get[' fo ']!= '" $_get[' fo ']: ';? > "size="/>
</p>
This is validation
[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 ' variable $a isset is true ';

Echo ' if (Isset ($_get[' fo ')) {
echo ' variable \ ' fo\ ' isset for true, variable available ';
}else{
echo ' variable \ ' fo\ ' isset is false, without variable setting ';
}

Echo ' if (Empty ($_get[' fo ')) {
The empty of the echo ' variable \ ' fo\ ' is true, i.e. null or void value ';
}else{
echo ' variable \ ' fo\ ' empty is false, has value ';
}

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

The case:echo ' fo no value, empty string ';
}elseif ($_get[' fo ']!= ') {
Echo ' fo has value, not for \ '. ';
}

The case of echo "if ($_get[' sex ']== ' m ') {///when there is no sex variable in the argument, an error occurs.
echo ' man ';
}elseif ($_get[' sex ']== ' f ') {
echo ' woman ';
}
?>

Third, other common library functions

(1) Ini_set ini_get--configurable parameter list
In order to make their programs have better compatibility in different platforms, many times we have to get the current operating environment parameters of PHP.
For example, we use the following:
Get the MAGIC_QUOTES_GPC state to determine whether we escaped (addslashes) data when the form was submitted;
Setting Max_execution_time to extend the execution time of the program;
Set the error_reporting to make your project in the development and operation phase switch;
Set Memory_limit to increase memory, etc...
(2) Ini_set (string varname, String newvalue)://Set parameters for environment configuration
Ini_get (String varname)://Get Parameters for environment configuration
The PHP ini_set function is the value of the SET option, which takes effect after the function is executed, and is invalidated when the script ends. Not all options can be changed by the function settings. These values can be set to see the list in the manual
In fact, you put PHP ini_set function and Ini_get combined to make the words, very good. For example, if you want to add your own file path to the configuration file, but you have permission to change php.ini, then you can combine two functions:
Ini_set (' include_path ', Ini_get (' include_path '). ':/your_include_dir: ');
(3) ChDir (dirname (__file__)); Switch to global.php directory
(4) Ob_start (' Ui_handler ')//Set output buffer handle to Ui_handler, that is, the system's first page is defined by the Ui_handler function
(5) int intval (mixed var, int [base]);
This function converts a variable to an integer type. The parameter base that can be omitted is the base of the transformation, and the default value is 10. The converted variable var can be an array or any type of variable other than the class.
(6) error_reporting (report_level) function--Set the error level of PHP and return to the current level
The report_level values are 0, 1, 2, 4, 8, 16, 、......、 4096, 8191
Example: Any number of the above options can be connected using "or" (with OR or |) to report all required levels of error. For example, the following code closes user-defined errors and warnings, performs certain actions, and then restores to the original error level:

Copy Code code as follows:
<?php

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. The difference between rand (Min,max) and Mt_rand (Min,max) If the optional Parameters min and Max,mt_rand () are not provided, the pseudo random number between 0 and Rand_max is returned. For example, want a random number between 5 and 15 (including 5 and 15), with Mt_rand (5, 15).
Many old libc random number generators have some uncertainties and unknown properties and are slow. The rand () function of PHP uses the libc random number generator by default. The Mt_rand () function is used informally to replace it. The function uses the known characteristics of the Mersenne twister as a random number generator, and it can produce a random numerical velocity of four times times faster than the 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 using parentheses. and echo returns void and does not return a value, so it cannot be used to assign a value.
Example:
Copy Code code as follows:
<?php $a = Echo ("55nav"); Error! Cannot be used to assign a value
echo "55nav"; 55nav
Echo ("55nav"); 55nav
Echo ("55nav", "com"); An error occurred, with parentheses not passing multiple arguments
echo "55nav", "com", "is", "web"; You can separate multiple values with commas without parentheses, and output the 55nav COM is web
echo "55nav is good web." The end display is good web for a row of 55nav is, regardless of whether the line is wrapped.
echo "$fistname com"; If $firstname = "55nav", 55nav com is output.
echo ' $firstname com '; Because of the use of single quotes, $firstname values are not output, but are output $firstname com12
?>

2) Print
Print () is the same as Echo (), but the echo speed is a little bit faster than print. It's not actually a function, so you don't have to use parentheses about it. However, if you want to pass more than one parameter to print (), a parse error occurs using parentheses. Note that print always returns 1, which is not the same as ECHO, which means you can use print to assign values, but it doesn't make sense.
Example:
Copy Code code as follows:
<?php $a = print ("55nav"); This is permissible.
echo $a; The value of $a is 14
?>;

3 Print_r Function--that is, to print the values of predefined variables
The Print_r function prints easily understandable information about a variable.
Syntax: Mixed print_r (mixed $expression [, BOOL return])
If the variable is a string, integer or float will output its value directly, and if the variable is an array, it will output a formatted array for readability, that is, the format of the key and value. is similar to object objects. Print_r has two parameters, the first is a variable, the second can be set to true, and if set to true, the string is returned, otherwise the Boolean value is true.
Example:
Copy Code code as follows:

<?php $a = "55nav";
$c = Print_r ($a);
Echo $c; The value of the $c is true
$c = Print_r ($a, ture);
Echo $c; $c value is a string of 55nav
?>

4) printf function
The printf function returns a formatted string.
Syntax: printf (format,arg1,arg2,arg++)
The parameter format is the format of the transformation, starting with the percent sign ("%") to the end of the converted character. The following are the possible format values:
*%%– return percent symbol
*%b– binary number
*%c– characters according to ASCII values
*%d– Signed decimal number
*%e– continuous counting method (e.g. 1.5e+3)
*%u– unsigned decimal number
*%f– floating-point number (Local settings Aware)
*%f– floating-point number (not local settings aware)
* Number of%o– octal
*%s– String
*%x– hexadecimal number (lowercase letter)
*%x– hexadecimal number (capital letter)
Arg1, Arg2, arg++ and other parameters will be inserted into the main string by percent semicolon (%) Symbol Place. The function is executed progressively, in the first% symbol, insert arg1, at the second% symbol, insert arg2, and so on. If the% symbol is more than the arg parameter, you must use a placeholder. After the placeholder is inserted into the% symbol, it is made up of numbers and "\$." You can use numbers to specify which parameters to display, see examples for details.
Example:
Copy Code code as follows:
<?php printf ("My name is%s%s.") "," 55nav "," com "); My name is 55nav com
printf ("My name is%2\ $s%1\ $s", "55nav", "com"); Add 1\$ or 2\$ before s ... Represents the location of the following parameter display, this row shows the 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 Code code as follows:
<?php sprintf ("My name is%1\ $s%1\ $s", "55nav", "com"); You'll find that there's 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: The content, type, and length of the output variable's content, type, or string. Commonly used to debug.
Example:
Copy Code code 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.