PHP (2) Common functions record some common library functions and common syntax for reference
I. PHP Manual
Php manual Chinese address http://php.net/manual/zh
II. some common operations
2.1 string operations
2.1.1 strpos-locate the first occurrence of a string
MixedStrpos(String $ haystack, mixed $ needle [, int $ offset = 0])
Returns the position of the number that needle first appeared in haystack.
Haystack
Search for the string.
Needle
If needle is not a string, it is converted to an integer and considered as a sequential value of characters.
Offset
If this parameter is provided, the search starts from the starting position of the character count of the string. Unlike strrpos () and strripos (), this offset cannot be a negative number.
2.1.2 substr-return the substring of the string
StringSubstr(String $ string, int $ start [, int $ length])
Returns the substring specified by the start and length parameters.
String
Input string.
Start
If start is not negative, the returned string starts from the start position of the string and starts from 0. For example, in the string "abcdef", the character at the position 0 is "a", and the character string at the position 2 is "c.
Return value:
If start is a negative number, the returned string starts from the start character at the end of the string.
If the string length is less than or equal to startFALSE.
2.1.3 str_split-convert a string to an array
ArraySplit(String $ pattern, string $ string [, int $ limit])
Converts a string to an array.
String. The length of each segment of split_length.
Return value:
If the optional split_length parameter is specified, each element in the returned array is a character block with the length of split_length. otherwise, each character block is a single character.
If split_length is less than 1, returnFALSE. If the split_length parameter exceeds the length of the string, the entire string is returned as only one element of the array.
2.1.4 explode-use one string to separate another string
ArrayExplode(String $ delimiter, string $ string [, int $ limit])
This function returns an array composed of strings. each element is a substring of a string, which is separated by a string delimiter as a boundary point.
Delimiter
Delimiter on the boundary.
String
The input string.
Limit
If the limit parameter is set and it is a positive number, the returned array contains up to limit elements, and the last element contains the rest of the string.
If the limit parameter is negative, all elements except the last-limit element are returned.
If the limit value is 0, it is regarded as 1.
This function returns an array composed of strings. each element is a substring of a string, which is separated by a string delimiter as a boundary point.
Returned value: if delimiter is a null string (""),Explode ()ReturnsFALSE. If delimiter contains a value that cannot be found in string and uses a negative limit value, an empty array is returned. Otherwise, an array containing a single string element is returned.
2.1.5 preg_split-use a regular expression to separate strings
ArrayPreg_split(String $ pattern, string $ subject [, int $ limit =-1 [, int $ flags = 0])
Use a regular expression to separate a given string.
Pattern
The search mode, in the string format.
Subject
Input string
Limit
If this parameter is specified, only limit substrings are allowed to be separated. The last substrings returned will contain all the remaining parts. When the limit value is-1, 0 or null, it indicates "unlimited". as the php standard, you can skip the flags setting using null.
Flags
Flags can be any combination marked below (bitwise OR operation | combination ):
PREG_SPLIT_NO_EMPTYIf this tag is set,
Preg_split ()Returns the non-empty parts after the separator.
PREG_SPLIT_DELIM_CAPTUREIf this flag is set, the parentheses expression in the separator mode will be captured and returned.
PREG_SPLIT_OFFSET_CAPTUREIf this flag is set, a string offset will be appended to each returned matching result. note: this will change every element in the returned array and make each element a substring separated by 0th elements, the first element is an array composed of the offsets of the substring in the subject. Return value: returns an array consisting of substrings separated by the pattern boundary.
2.2 Array Operations
2.2.1 array-create an array
ArrayArray([Mixed $...])
Create an array.
The syntax "index => values" is separated by commas (,), which defines the index and value. The index can be a string or number. If the index is omitted, an integer index starting from 0 is automatically generated. If the index is an integer, the next index will be the currently largest integer index + 1. Note that if two identical indexes are defined, the next one will overwrite the previous one.
Return value: returns the array created based on the parameter. You can use the => operator to provide the index for the parameter.
2.2.2 array_push-push one or more units to the end of the array (in the stack)
IntArray_push(Array & $ array, mixed $ var [, mixed $...])
Array_push ()Use array as a stack and press the input variable to the end of array. The length of array increases according to the number of variables in the stack.
Array. The value of var. Return value: returns the number of elements in the processed array.
2.3 create an index file/add a header file
2.3.1 include statement include and run the specified file
The contained file is first searched based on the path given by the parameter. If no directory is provided (only the file name), it is searched based on the directory specified by include_path. If this file is not found in include_path, include is finally located in the directory where the script file is called and in the current working directory. If the file is not found at the end, the include structure will issue a warning; this is different from require, the latter will issue a fatal error.
If the path is defined, whether it is an absolute path (starting with a drive letter or \ in Windows, starting with/in Unix/Linux) or the relative path of the current directory (starting. or ..) -- include_path will be completely ignored. For example, if a file starts with ../, the parser searches for the file in the parent directory of the current directory.
When a file is included, the code contained in the file inherits the variable range of the row where the include is located. From this point on, any variables available to the calling file in this row are also available in the called file. However, all functions and classes defined in the inclusion file have a global scope.
2.3.2 The require statement contains and runs the specified file
Require and include are almost the same, except for different methods of handling failures.RequireGenerated when an error occursE_COMPILE_ERRORLevel error. In other words, this will cause the script to stop and include will only generate warnings (E_WARNING), The script continues to run.
III. common database functions
Time 3.1
3.1.1 time-returns the current Unix timestamp
IntTime(Void)
Returns the number of seconds from the Unix epoch (January 1, January 1, 1970 00:00:00 GMT) to the current time.
3.1.2 date-format a local time/date
StringDate(String $ format [, int $ timestamp])
Returns the string generated by the integer timestamp according to the given format string. If no timestamp is provided, the current local time is used. In other words, timestamp is optional and the default value is time ().
Specific format: http://php.net/manual/zh/function.date.php
3.1.3 date_default_timezone_get-get the default time zone used by all the datetime functions in the script
StringDate_default_timezone_get(Void)
This function returns the default time zone.
3.1.4 date_default_timezone_set-set the default time zone used for all date and time functions in a script
BoolDate_default_timezone_set(String $ timezone_identifier)
Set the default time zone for all date and time functions.
Timezone_identifier
The time zone identifier, such as UTC or Asia/Shanghai ). Legal identifier list see http://php.net/manual/zh/timezones.php
Returned value: if the timezone_identifier parameter is invalidFALSEOtherwise, returnTRUE.
3.2 JSON format operations
3.2.1 json_encode-JSON encoding of variables
StringJson_encode(Mixed $ value [, int $ options = 0 [, int $ depth = 512])
Return the JSON format of the value.
Value
The value to be encoded can be any data type except the resource type. This function can only accept UTF-8-encoded data
Options
Binary mask constant. See http://php.net/manual/zh/json.constants.php for details
Depth
Set the maximum depth. Must be greater than 0.
Return value: if the request is successful, a JSON string is returned or if the request fails.FALSE.
3.2.2 json_decode-decodes strings in JSON format
MixedJson_decode(String $ json [, bool $ assoc = false [, int $ depth = 512 [, int $ options = 0])
Accept a JSON string and convert it to a PHP variable
Json string to be decoded. This function can only accept UTF-8-encoded data assoc when this parameter isTRUEWill return array instead of object. Depth sets the maximum depth. Must be greater than 0. Options Binary mask constant. Only supportedJSON_BIGINT_AS_STRING
3.3 file operations
3.3.1 fopen-open a file or URL
ResourceFopen(String $ filename, string $ mode [, bool $ use_include_path = false [, resource $ context])
Fopen ()Bind the name resource specified by filename to a stream.
Filename
If filename is in the format of "scheme: //...", it is treated as a URL. PHP will use the search protocol processor (also known as the Encapsulation Protocol) to process this mode. If the protocol has not yet registered the Encapsulation Protocol, PHP will send a message to help check the potential problems in the script and continue executing the filename as a normal file name.
If PHP considers filename to be a local file, it will try to open a stream on the file. This file must be accessible by PHP. Therefore, you need to confirm that the file access permission permits this access. If the security mode or open_basedir is activated, further restrictions are applied.
Mode
The mode parameter specifies the access type required for the stream. It can be the following:
Fopen ()List of possible values of mode in
Mode description
'R' |
Open the file in read-only mode and point the file pointer to the file header. |
'R +' |
Open in read/write mode and point the file pointer to the file header. |
'W' |
Open in writing mode, point the file pointer to the file header, and cut the file size to zero. If the file does not exist, try to create it. |
'W +' |
Open in read/write mode, point the file pointer to the file header, and cut the file size to zero. If the file does not exist, try to create it. |
'A' |
Open in writing mode and point the file pointer to the end of the file. If the file does not exist, try to create it. |
'A +' |
Open in read/write mode and point the file pointer to the end of the file. If the file does not exist, try to create it. |
'X' |
Create and open the file in writing mode, and point the file pointer to the file header. If the file already existsFopen ()Call failed and returnFALSEAnd generateE_WARNINGLevel error message. If the file does not exist, try to create it. This is equivalent to specifying the O_EXCL | O_CREAT mark for the underlying open (2) system call. |
'X +' |
Create and open in read/write mode. Other actions are the same as those of 'X. |
Use_include_path
If you also need to search for files in include_path, you can set the third optional parameter use_include_path to '1' orTRUE.
Context
Context
Return value:
Returns the file pointer resource when the operation succeeds. if the operation fails, this function returnsFALSE.
Error message: if an error occurs,E_WARNINGError. You can use @ to block errors.
3.3.2 fgets-read a row from the object pointer
StringFgets(Resource $ handle [, int $ length])
Read a row from the file pointer.
Handle
The file pointer must be valid and must be directed to a file successfully opened by fopen () or fsockopen () (not closed by fclose ).
Length
Read a row from the file pointed to by handle and return a string of up to length-1 bytes. When a line break (including the returned value), EOF, or the length-1 byte is read, it is stopped ). If length is not specified, the default value is 1 K, or 1024 bytes.
Return value:
Read the length-1 byte from the file pointed to by the pointer handle and then return the string. If no more data exists in the file pointer, the system returnsFALSE.
Returned when an error occursFALSE.
3.3.3 fread-read files (binary files can be safely used)
StringFread(Resource $ handle, int $ length)
Fread ()Read a maximum of length bytes from the file pointer handle. This function stops reading files in the following situations:
Read length bytes
Reached the end of the file (EOF)
Handle
A file system pointer is a resource typically created by fopen ).
Length
Read a maximum of length bytes.
Return value: returns the string to be read, or returns the string if it fails.FALSE.
3.3.4 fwrite-write a file (which can be safely used for binary files)
IntFwrite(Resource $ handle, string $ string [, int $ length])
Fwrite ()Write the string content to the handle of the file pointer.
Handle
A file system pointer is a resource typically created by fopen ).
String
String to be written
Ength
If length is specified, the write will stop after the length byte is written or the string is written.
Return value:Fwrite ()Returns the number of written characters. If an error occurs, it is returned.FALSE.
3.3.5 fclose-close an opened file pointer
BoolFclose(Resource $ handle)
Close the file to which handle points.
Handle
The file pointer must be valid and can be successfully opened through fopen () or fsockopen.
Return value: if the request is successfulTRUE, Or return when the failure occurs.FALSE.
3.3.6 file_get_contents-read the entire file into a string
StringFile_get_contents(String $ filename [, bool $ use_include_path = false [, resource $ context [, int $ offset =-1 [, int $ maxlen])
Like file (), onlyFile_get_contents ()Read the file into a string. The content with the length of maxlen will be read at the position specified by the offset parameter. If it fails,File_get_contents ()ReturnsFALSE.
This function does not need to open files or close file streams! Very convenient.
File_get_contents ()A function is the preferred method for reading the content of a file into a string. If the operating system supports it, the memory ing technology will be used to enhance the performance.
If you want to open a URL with special characters (such as spaces), you need to use urlencode () for URL encoding.
Parameter description
Path |
Required. Specifies the file to be read. |
Include_path |
Optional. If you want to search for files in include_path, you can set this parameter to "1 ". |
Context |
Optional. Specifies the file handle environment. Context is a set of options that can modify the behavior of a stream. If null is used, this parameter is ignored. |
Start |
Optional. Specifies the location where the file starts reading. This parameter is newly added in PHP 5.1. |
Max_length |
Optional. The number of bytes to read. This parameter is newly added in PHP 5.1. |
Example:
$ Homepage = file_get_contents ('http: // www.example.com /');
Echo $ homepage;
?>