Home > Backend Development > PHP Tutorial > Summary of common functions based on PHP (array, string, time, file operation)_PHP tutorial

Summary of common functions based on PHP (array, string, time, file operation)_PHP tutorial

WBOY
Release: 2016-07-21 15:03:12
Original
732 people have browsed it

Array: [Key Point 1]
implode (separated, arr) concatenates array value data according to specified characters
For example:
$arr=array('1', '2','3','4');
$str=implode('-',$arr);
explode([separate],arr) splits a string according to the specified rules, The return value is the array alias join
array_merge() to merge one or more arrays
array_combine(array keys, array values) to create an array, using the value of one array as its key name and the value of the other array as its key name. Value
For example:
$a = array('green','red','yellow');
$b = array('avocado','apple','banana');
$c = array_combine($a, $b);
print_r($c);
/* Outputs:
Array
(
[green] => avocado
[red] => apple
[yellow] => banana
)
*/
array_push(arr,str) Push one or more cells to the end of the array (push)
array_unique(arr) removes duplicate values ​​in the array
array_search() searches for a given value in the array, and returns the corresponding key name if successful
array_values() returns all values ​​in the array
array_keys() Returns all key names in the array
count(arr) Counts the number of units in the array or the number of attributes in the object sizeof()
is_array(arr) Checks whether the variable is an array
sort(arr) Sort the array
array_flip(arr) Exchange the keys and values ​​in the array
Note that the value in trans needs to be a legal key name, for example, it needs to be integer or string. A warning will be emitted if the value is of the wrong type, and the key/value pairs in question will not be reversed.
key(arr) returns the key name of the current element in the array
current(arr) returns the value pointed by the current pointer
next returns the value pointed by the next pointer
For example

Copy code The code is as follows:

$array = array (
'fruit1' => 'apple',
'fruit2 ' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple'
) ;
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple ') {
echo key($array).'
';
}
next($array);
}

reset(arr)数组的内部指针指向第一个单元
array_chunk( array input, int size [, bool preserve_keys])) 将一个数组分割成多个
将一个数组分割成多个数组,其中每个数组的单元数目由 size 决定。最后一个数组的单元数目可能会少几个。得到的数组是一个多维数组中的单元,其索引从零开始。
将可选参数 preserve_keys 设为 TRUE,可以使 PHP 保留输入数组中原来的键名。如果你指定了 FALSE,那每个结果数组将用从零开始的新数字索引。默认值是 FALSE。

字符串【重点2】
trim(str) 消除字符串两边的空格
rtrim()
addslashes在指定预定义字符前加\
strlen(str) 取字符串长度
substr(str,start,length) 截取指定字符串中指定长度的字符
strstr(str,search)函数用于获取一个指定字符串在另一个字符串中首次出现的位置到后者末尾的子字符串。与 strchr相同
strpos(str,search) 查找字符串中某字符第一次出现的位置
str_replace(search,replace,str) 字符串替换
ucfirst(str) 将字符串第一个字符大写
strtolower 变小写
ucwords(str) 将字符串每个字的第一个字母大写
strcmp(str1,str2)函数用来对两个字符串进行比较
substr_count()函数检索子串出现的次数
正则相关字符串函数:
preg_match(pattern,subject,matches) 在subject字符串中搜索与 pattern 给出的正则表达式相匹配的内容,匹配后的结果存放在matches里边,matches[0]全部匹配内容,matches[1]第一个模式单元matches[1]第二模式单元,以此类推.
preg_match_all(pattern,subject,matches)全局匹配,其余的preg_match函数相似
preg_replace(pattern,replacement,str) 执行正则表达式的搜索和替换,三种[string,string][array,string][array,array]
preg_split(pattern,str) 用正则表达式分割字符串
preg_grep(pattern,array)用正则表达式匹配数组的值,返回一个新的数组信息

时间【重点3】
PHP的日期时间函数date()
1,年-月-日
echo date('Y-m-j');
2007-02-6
echo date('y-n-j');
07-2-6
大写Y表示年四位数字,而小写y表示年的两位数字;
小写m表示月份的数字(带前导),而小写n则表示不带前导的月份数字。
echo date('Y-M-j');
2007-Feb-6
echo date('Y-m-d');
2007-02-06
大写M表示月份的3个缩写字符,而小写m则表示月份的数字(带前导0);
没有大写的J,只有小写j表示月份的日期,无前导o;若需要月份带前导则使用小写d。
echo date('Y-M-j');
2007-Feb-6
echo date('Y-F-jS');
2007-February-6th
大写M表示月份的3个缩写字符,而大写F表示月份的英文全写。(没有小写f)
大写S表示日期的后缀,比如“st”、“nd”、“rd”和“th”,具体看日期数字为何。

小结:
表示年可以用大写的Y和小写y;
表示月可以用大写F、大写M、小写m和小写n(分别表示字符和数字的两种方式);
表示日可以用小写d和小写j,大写S表示日期的后缀。

2,时:分:秒
默认情况下,PHP解释显示的时间为“格林威治标准时间”,与我们本地的时间相差8个小时。
echo date('g:i:s a');
5:56:57 am
echo date('h:i:s A');
05:56:57 AM
小写g表示12小时制,无前导0,而小写h则表示有前导0的12小时制。
当使用12小时制时需要表明上下午,小写a表示小写的“am”和“pm”,大写A表示大写的“AM”和“PM”。
echo date('G:i:s');
14:02:26
大写G表示24小时制的小时数,但是不带前导的;使用大写的H表示带前导的24小时制小时数
小结:
字母g表示小时不带前导,字母h表示小时带前导;
小写g、h表示12小时制,大写G、H表示24小时制。

3,闰年、星期、天
echo date('L');
今年是否闰年:0
echo date('l');
今天是:Tuesday
echo date('D');
今天是:Tue
大写L表示判断今年是否闰年,布尔值,为真返回1,否则为0;
小写l表示当天是星期几的英文全写(Tuesday);
而使用大写D表示星期几的3个字符缩写(Tue)。
echo date('w');
今天星期:2
echo date('W');
本周是全年中的第 06 周
小写w表示星期几,数字形式表示
大写W表示一年中的星期数
echo date('t');
本月是 28 天
echo date('z');
今天是今年的第 36 天
小写t表示当前月份又多少天
小写z表示今天是本年中第几天

4, others
echo date('T');
UTC
Capital T represents the time zone setting of the server
echo date('I');
0
Capital I means to determine whether the current daylight saving time is, if true, return 1, otherwise 0
echo date('U');
1170769424
Capital U means since January 1970 The total number of seconds from the 1st to the present is the UNIX timestamp of the Unix time epoch.
echo date('c');
2007-02-06T14:24:43+00:00
Lowercase c represents the ISO8601 date, the date format is YYYY-MM-DD, separated by the letter T Date and time, the time format is HH:MM:SS, and the time zone is expressed using the offset from Greenwich Mean Time (GMT).
echo date('r');
Tue, 06 Feb 2007 14:25:52 +0000
Lowercase r represents the RFC822 date.
The small date() function shows the power and charm of PHP. Let’s compare it to ASP, haha.
checkdate($month,$date,$year)
This function returns true if the applied value constitutes a valid date. For example, for the error date February 31, 2005, this function returns false.
This function can be used to check and validate a date before it is used in calculations or saved in the database.

Copy code The code is as follows:

// returns false
echo checkdate(2 ,30,2005) ? "valid" : "invalid";
// returns true
echo checkdate(4,6,2010) ? "valid" : "invalid";
?>

getdate($ts)
Without arguments, this function returns the current date and time in a combined array. Each element in the array represents a specific component of the date/time value. An optional time stamp argument can be submitted to the function to obtain a date/time value corresponding to the time stamp.
Apply this function to obtain a series of discrete, easily separable date/time values.
Copy code The code is as follows:

// get date as associative array
$ arr = getdate();
echo "Date is " . $arr['mday'] . " " . $arr['weekday'] . " " . $arr['year'];
echo " Time is " . $arr['hours'] . ":" . $arr['minutes'];
?>

mktime($hour, $minute, $second, $month, $day, $year)
This function does the opposite of getdate(): it generates a UNIX time stamp from a series of date and time values ​​(GMT time 1970 1 The number of seconds that have elapsed since the 1st of the month). When no arguments are used, it generates a UNIX time stamp of the current time.
Use this function to obtain the UNIX time label of the immediate time. Such timestamps are commonly used in many databases and programming languages.
Copy code The code is as follows:

// returns timestamp for 13:15:23 7 -Jun-2006
echo mktime(13,15,23,6,7,2006);
?>

date($format, $ts)
This function formats a UNIX time stamp into a human-readable date string. It is the most powerful function in the PHP date/time API and can be used to convert integer time labels into the required string format in a series of correction values.
Apply this function when formatting time or date for display.
Copy code The code is as follows:

// format current date
// returns "13-Sep-2005 01:16 PM"
echo date("d-M-Y h:i A", mktime());
?>

strtotime( $str)
This function converts a human-readable English date/time string into a UNIX time tag.
Apply this function to convert a non-standardized date/time string into a standard, compatible UNIX time tag.
Copy code The code is as follows:

// returns 13-Sep-05
echo date("d-M-y", strtotime("today"));
// returns 14-Sep-05
echo date("d-M-y", strtotime("tomorrow"));
// returns 16-Sep-05
echo date("d-M-y", strtotime("today +3 days"));
?>

strftime($format,$ ts)
As defined by the previous setlocale() function, this function formats the UNIX time stamp into a date string suitable for the current environment.
Apply this function to create a date string compatible with the current environment.
Copy code The code is as follows:

// set locale to France (on Windows)
setlocale(LC_TIME, "fra_fra");
// format month/day names
// as per locale setting
// returns "septembre" and "mardi"
echo strftime(" Month: %B ");
echo strftime("Day: %A ");
?>

microtime()
As defined by the previous setlocale() function, this function formats the UNIX time stamp into a date string suitable for the current environment.
Apply this function to create a date string compatible with the current environment.
Copy code The code is as follows:

// get starting value
$start = microtime();
// run some code
for ($x=0; $x<1000; $x++) {
$null = $x * $x;
}
// get ending value
$end = microtime();
// calculate time taken for code execution
echo "Elapsed time: " . ($end - $start) ." sec";
?>

gmmktime($hour, $minute, $second, $month, $day, $year)
This function consists of a series of GMT times The date and time value represented generates a UNIX time stamp. When no arguments are used, it generates a UNIX time stamp of the current GMT time.
Use this function to obtain the UNIX time label of GMT real-time time.
Copy code The code is as follows:

// returns timestamp for 12:25:23 9 -Jul-2006
echo gmmktime(12,25,23,7,9,2006);
?>

gmdate($format, $ts)
This function formats a UNIX time stamp into a human-readable date string. This date string is expressed in GMT (not local time).
Apply this function when using GMT to represent the time label.
Copy code The code is as follows:

// format current date into GMT
/ / returns "13-Sep-2005 08:32 AM"
echo gmdate("d-M-Y h:i A", mktime());
?>

date_default_timezone_set($ tz), date_default_timezone_get()
All date/time function calls after this function set and restore the default time zone.
Note: This function is only valid in PHP 5.1+.
This function is a convenient shortcut for setting the time zone for future time operations.
Copy code The code is as follows:

// set timezone to UTC
date_default_timezone_set( 'UTC');
?>

Copy code The code is as follows:

< ;?php
//Today
$today = date("Y-m-d");
//Yesterday
$yesterday = date("Y-m-d", strtotime(date("Y-m-d"))- 86400);
//Last week
$lastweek_start = date("Y-m-d H:i:s",mktime(0, 0, 0,date("m"),date("d")-date ("w")+1-7,date("Y")));
$lastweek_end = date("Y-m-d H:i:s",mktime(23,59,59,date("m") ,date("d")-date("w")+7-7,date("Y")));
//This week
$thisweek_start = date("Y-m-d H:i:s ",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
$thisweek_end = date( "Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));
//Last month
$lastmonth_start = date("Y-m-d H:i:s",mktime(0, 0, 0,date("m")-1,1,date("Y"))) ;
$lastmonth_end = date("Y-m-d H:i:s",mktime(23,59,59,date("m") ,0,date("Y")));
//this Month
$thismonth_start = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y")));
$thismonth_end = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));
//Not available in this quarter Number of days in the last month
$getMonthDays = date("t",mktime(0, 0, 0,date('n')+(date('n')-1)%3,1,date("Y ")));
//This quarter/
$thisquarter_start = date('Y-m-d H:i:s', mktime(0, 0, 0,date('n')-(date('n ')-1)%3,1,date('Y')));
$thisquarter_end = date('Y-m-d H:i:s', mktime(23,59,59,date('n') +(date('n')-1)%3,$getMonthDays,date('Y')));

File operation [Key point 4]
file_exists(filename) Whether the file or directory exists
filesize(filename) Get the file size
pathinfo(filename) Return the directory name, base name and Associative array of extensions
$path_parts = pathinfo("/www/htdocs/index.html");
echo $path_parts["dirname"] . "n";
echo $path_parts["basename "] . "n";
echo $path_parts["extension"] . "n";
/www/htdocsindex.htmlhtml
mkdir(dirname) Create directory
rmdir(dirname) Delete empty Directory
fopen(filename,mode) Open file
fclose(fp) Close file
fwrite(fp,str,length) Write file
file_put_contents(filename,content) Save content to file
file_get_contents(filename) Read content from file
fread(fp,length) Read file
fgets() Read a line from file pointer
fgetc() Read characters from file pointer
file() reads the entire file into an array, and each unit in the array is a corresponding line in the file
readfile() reads a file and writes it to the output buffer
copy(filename1, filename2) Copy file
unlink(filename) Delete file
rename(filename1,filename2) Rename file or directory
$text = iconv('gbk','utf-8','Gao Zhiwei') ;///Convert gbk encoding to utf-8

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327876.htmlTechArticleArray: [Key Point 1] implode (separated, arr) concatenates array value data according to specified characters. For example: $ arr=array('1','2','3','4'); $str=implode('-',$arr); explode([separated], arr) according to the specified rules...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template