文章目录
PHP基本函数学习使用
在后勤系统学习框架同时使用基本的函数简化操作,从php手册中做笔记,方便以后查阅,大部分内容来自php手册加上实践例子
PHP Manual
Variable handing 函数
intval
获取变量的整数值
int intval(mixed $var [,int $base = 10])
通过使用指定的进制base转换(默认是十进制),返回变量var的integer数值。不能用于object,否则会产生E_NOTICE错误并返回1.
Directiory函数
readdir
(PHP 4, PHP 5, PHP 7)
readdir — 从目录句柄中读取条目[包括文件和文件夹]
string readdir ([ resource $dir_handle ] )
- 参数
- dir_handle
目录句柄的 resource,之前由 opendir() 打开
- 返回值
成功则返回文件名 或者在失败时返回 FALSE
此函数可能返回布尔值 FALSE,但也可能返回等同于 FALSE 的非布尔值。
- 范例
请留意下面例子中检查 readdir() 返回值的风格。这里明确地测试返回值是否全等于(值和类型都相同——更多信息参见比较运算符)FALSE,否则任何目录项的名称求值为 FALSE 的都会导致循环停止(例如一个目录名为"0")。
<?php
// 注意在 4.0.0-RC2 之前不存在 !== 运算符
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Files:\n";
/* 这是正确地遍历目录方法 */
while (false !== ($file = readdir($handle))) {
echo "$file\n";
}
/* 这是错误地遍历目录的方法 */
while ($file = readdir($handle)) {
echo "$file\n";
}
closedir($handle);
}
?>
列出当前目录的所有文件并去掉 . 和 ..
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
字符串函数
strpos
查找字符串首次出现的位置
mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
返回needle在haystack中首次出现的数字位置
- 参数
- haystack
在该字符串中进行查找。
2. needle
如果 needle 不是一个字符串,那么它将被转换为整型并被视为字符的顺序值。
3. offset
如果提供了此参数,搜索会从字符串该字符数的起始位置开始统计。 如果是负数,搜索会从字符串结尾指定字符数开始。
- 返回值
返回 needle 存在于 haystack 字符串起始的位置(独立于 offset)。同时注意字符串位置是从0开始,而不是从1开始的。
如果没找到 needle,将返回 FALSE。
- 范例
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// 注意这里使用的是 ===。简单的 == 不能像我们期待的那样工作,
// 因为 'a' 是第 0 位置上的(第一个)字符。
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>
trim
去除字符串首尾处的空白字符(或其他字符)
string trim(string $str [,string $charlist = "\r\n\r\0\x0B"])
此函数返回字符串str去除首尾空白字符后的结果。如果不指定第二参数,将去除以下字符:
" " ,普通空格符
"\t",制表符
"\n",换行符
"\r",回车符
"\0",空字节符
"\x0B",垂直制表字符
substr_count
substr_count — 计算字串出现的次数
- 说明
int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )
substr_count() 返回子字符串needle 在字符串 haystack 中出现的次数。注意 needle 区分大小写。
Note:
该函数不会计算重叠字符串。参见下面的例子。
- 参数
- haystack
在此字符串中进行搜索。
- needle
要搜索的字符串。
- offset
开始计数的偏移位置。如果是负数,就从字符的末尾开始统计。
- length
指定偏移位置之后的最大搜索长度。如果偏移量加上这个长度的和大于 haystack 的总长度,则打印警告信息。 负数的长度 length 是从 haystack 的末尾开始统计的。
- 返回值
该函数返回整型。
- 范例
Example #1 substr_count() 范例
<?php
$text = 'This is a test';
echo strlen($text); // 14
echo substr_count($text, 'is'); // 2
// 字符串被简化为 's is a test',因此输出 1
echo substr_count($text, 'is', 3);
// 字符串被简化为 's i',所以输出 0
echo substr_count($text, 'is', 3, 3);
// 因为 5+10 > 14,所以生成警告
echo substr_count($text, 'is', 5, 10);
// 输出 1,因为该函数不计算重叠字符串
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd');
?>
HTTP函数
header
向客户端发送原始的 HTTP 报头,即必须在任何实际的输出被发送之前调用 header() 函数,供前端跨域使用(不同服务器间js发送http请求)
在项目基类控制器中设置如下:
class BaseController extends ApiController
{
function _initialize()
{
header('Access-Control-Allow-Origin:*');//允许所有来源访问
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');//允许访问的方式
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description, Authorization');
知识充电:
HTTP 响应首部字段
- Access-Control-Allow-Origin
响应首部中可以携带一个 Access-Control-Allow-Origin 字段,其语法如下:
Access-Control-Allow-Origin: <origin> | *
其中,origin 参数的值指定了允许访问该资源的外域URI。
对于不需要携带身份凭证的请求,服务器可以指定该字段的值为通配符,表示允许来自所有域的请求。
例如,下面的字段值将允许来自 http://mozilla.com 的请求:
Access-Control-Allow-Origin: http://mozilla.com
如果服务端指定了具体的域名而非“*”,那么响应首部中的 Vary 字段的值必须包含 Origin。这将告诉客户端:服务器对不同的源站返回不同的内容。
- Access-Control-Expose-Headers
Access-Control-Expose-Headers头让服务器把允许浏览器访问的头放入白名单,例如:
Access-Control-Expose-Headers: X-My-Custom-Header, X-Another-Custom-Header
- Access-Control-Max-Age
Access-Control-Max-Age 头指定了preflight请求的结果能够被缓存多久:
Access-Control-Max-Age: <delta-seconds>
delta-seconds 参数表示preflight请求的结果在多少秒内有效。
- Access-Control-Allow-Credentials
Access-Control-Allow-Credentials 头指定了当浏览器的credentials设置为true时是否允许浏览器读取response的内容。当用在对preflight预检测请求的响应中时,它指定了实际的请求是否可以使用credentials。请注意:简单 GET 请求不会被预检;如果对此类请求的响应中不包含该字段,这个响应将被忽略掉,并且浏览器也不会将相应内容返回给网页。
Access-Control-Allow-Credentials: true
- Access-Control-Allow-Methods
Access-Control-Allow-Methods 首部字段用于预检请求的响应。其指明了实际请求所允许使用的 HTTP 方法。
Access-Control-Allow-Methods: <method>[, <method>]*
- Access-Control-Allow-Headers
Access-Control-Allow-Headers 首部字段用于预检请求的响应。其指明了实际请求中允许携带的首部字段。
Access-Control-Allow-Headers: <field-name>[, <field-name>]*
范例一:
<?PHP
Header("Location: http://www.jb51.net";);
exit;//在每个重定向之后都必须加上“exit",避免发生错误后,继续执行。
?>
<?php
header("refresh:2;url=http://www.jb51.net");
echo "正在加载,请稍等...<br>
三秒后自动跳转至<a href="http://www.jb51.net" mce_href="http://www.jb51.net">百度</a>...";
?>
范例二:禁止页面在IE中缓存
使浏览者每次都能得到最新的资料,而不是 Proxy 或 cache 中的资料:
<?PHP
header( 'Expires: Fri, 4 Dec 2009 09:00:00 GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' ); //兼容http1.0和https
?>
CacheControl = no-cache Pragma=no-cache Expires = -1
如果服务器上的网页经常变化,就把Expires设置为-1,表示立即过期。如果一个网页每天凌晨1点更新,可以把Expires设置为第二天的凌晨1点。当HTTP1.1服务器指定CacheControl = no-cache时,浏览器就不会缓存该网页。
旧式 HTTP 1.0 服务器不能使用 Cache-Control 标题。所以为了向后兼容 HTTP 1.0 服务器,IE使用Pragma:no-cache 标题对 HTTP 提供特殊支持。如果客户端通过安全连接 (https://) 与服务器通讯,且服务器在响应中返回 Pragma:no-cache 标题,则 Internet Explorer 不会缓存此响应。
注意:Pragma:no-cache 仅当在安全连接中使用时才防止缓存,如果在非安全页中使用,处理方式与 Expires:-1 相同,该页将被缓存,但被标记为立即过期。
http-equiv meta标记:
在html页面中可以用http-equiv meta来标记指定的http消息头部。老版本的IE可能不支持html meta标记,所以最好使用http消息头部来禁用缓存。
范例三: 让使用者的浏览器出现找不到档案的信息。
网上很多资料这样写:php的函数header()可以向浏览器发送Status标头,
如 header(”Status: 404 Not Found”)。但实际上浏览器返回的响应却是:
HTTP/1.x 200 OK
Date: Thu, 03 Aug 2006 07:49:11 GMT
Server: Apache/2.0.55 (Win32) PHP/5.0.5
X-Powered-By: PHP/5.0.5
Status: 404 Not Found
Content-Length: 0
Keep-Alive: timeout=15, max=98
Connection: Keep-Alive
Content-Type: text/html
正确的写法是:
header(”http/1.1 404 Not Found”);
第一部分为HTTP协议的版本(HTTP-Version);第二部分为状态代码(Status);第三部分为原因短语(Reason-Phrase)。
范例四:让使用者下载档案( 隐藏文件的位置 )
html标签 就可以实现普通文件下载。如果为了保密文件,就不能把文件链接告诉别人,可以用header函数实现文件下载。
<?php
header("Content-type: application/x-gzip");
header("Content-Disposition: attachment; filename=文件名/");
header("Content-Description: PHP3 Generated Data");
?>
范例五:header函数前输入内容
一般来说在header函数前不能输出html内容,类似的还有setcookie() 和 session 函数,这些函数需要在输出流中增加消息头部信息。如果在header()执行之前有echo等语句,当后面遇到header()时,就会报出 “Warning: Cannot modify header information - headers already sent by ….”错误。就是说在这些函数的前面不能有任何文字、空行、回车等,而且最好在header()函数后加上exit()函数。例如下面的错误写法,在两个php代码段之间有一个空行:
//some code here
?>
//这里应该是一个空行
header(”http/1.1 403 Forbidden”);
exit();
?>
原因是:PHP脚本开始执行 时,它可以同时发送http消息头部(标题)信息和主体信息. http消息头部(来自 header() 或 SetCookie() 函数)并不会立即发送,相反,它被保存到一个列表中. 这样就可以允许你修改标题信息,包括缺省的标题(例如 Content-Type 标题).但是,一旦脚本发送了任何非标题的输出(例如,使用 HTML 或 print() 调用),那么PHP就必须先发送完所有的Header,然后终止 HTTP header.而后继续发送主体数据.从这时开始,任何添加或修改Header信息的试图都是不允许的,并会发送上述的错误消息之一。
解决办法:
修改php.ini打开缓存(output_buffering),或者在程序中使用缓存函数ob_start(),ob_end_flush()等。原理是:output_buffering被启用时,在脚本发送输出时,PHP并不发送HTTP header。相反,它将此输出通过管道(pipe)输入到动态增加的缓存中(只能在PHP 4.0中使用,它具有中央化的输出机制)。你仍然可以修改/添加header,或者设置cookie,因为header实际上并没有发送。当全部脚本终止时,PHP将自动发送HTTP header到浏览器,然后再发送输出缓冲中的内容。
在PHP中用header(“location:test.php”)进行跳转要注意以下几点:
1、location和“:”号间不能有空格,否则会出错.
2、在用header前不能有任何的输出,包括include的页面中标签“?>”后不能有空格.
3、header后的PHP代码还会被执行.
PHP的 header 跳转之前不能有任何内容输出,因为PHP开始执行的时候就已经向浏览器送出HTTP头信息,之后就不再允许更改了.
但是如果必须要在输出之后再处理header信息的话可以使用 ob_start() ob_end_flush() 来缓存一下要发送的内容,等到header继续再发送内容.
或者一个更简单的办法,修改php.ini,找到 output_buffering=Off 修改为 output_buffering=4096.
PHP 手册实例应用
1:您可以使用heder命令,强制使浏览器使用新鲜的内容(无缓存) 。
也可以给网址增加了一个唯一的编号,使其每次都读取新的内容,避免缓存。
<?
print "<img src="cs.jpg" mce_src="cs.jpg">"; //通常读取的是缓存文件
?>
<?
print "<img src="cs.jpg?".time()."" mce_src="cs.jpg?".time()."">"; //增加了唯一的编号,使浏览器重新请求
w//print "<img src="cs.jpg?".rand(100,999)."" mce_src="cs.jpg?".rand(100,999)."">";
?>
2: 下面是个很好的函数,将图片传送给浏览器显示。
<?php
function PE_img_by_path($PE_imgpath = "")
{
if (file_exists($PE_imgpath)) {
$PE_imgarray = pathinfo($PE_imgpath);
$iconcontent = file_get_contents($PE_imgpath);
header("Content-type: image/" . $PE_imgarray["extension"]);
header('Content-length: ' . strlen($iconcontent));
echo $iconcontent;
die(0);
}
return false;
}
?>
更多的实例:
<?php
// ok
header('HTTP/1.1 200 OK');
//设置一个404头:
header('HTTP/1.1 404 Not Found');
//设置地址被永久的重定向
header('HTTP/1.1 301 Moved Permanently');
//转到一个新地址
header('Location: http://www.baidu.com');
//文件延迟转向:
header('Refresh: 10; url=http://www.example.org/');
print 'You will be redirected in 10 seconds';
//当然,也可以使用html语法实现
// <meta http-equiv="refresh" content="10;http://www.example.org/ />
// override X-Powered-By: PHP:
header('X-Powered-By: PHP/4.4.0');
header('X-Powered-By: Brain/0.6b');
//文档语言
header('Content-language: en');
//告诉浏览器最后一次修改时间
$time = time() - 60; // or filemtime($fn), etc
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $time).' GMT');
//告诉浏览器文档内容没有发生改变
header('HTTP/1.1 304 Not Modified');
//设置内容长度
header('Content-Length: 1234');
//设置为一个下载类型
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.zip"');
header('Content-Transfer-Encoding: binary');
// load the file to send:
readfile('example.zip');
// 对当前文档禁用缓存
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Pragma: no-cache');
//设置内容类型:
header('Content-Type: text/html; charset=iso-8859-1');
header('Content-Type: text/html; charset=utf-8');
header('Content-Type: text/plain'); //纯文本格式
header('Content-Type: image/jpeg'); //JPG图片
header('Content-Type: application/zip'); // ZIP文件
header('Content-Type: application/pdf'); // PDF文件
header('Content-Type: audio/mpeg'); // 音频文件
header('Content-Type: application/x-shockwave-flash'); //Flash动画
//显示登陆对话框
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');
print 'Text that will be displayed if the user hits cancel or ';
print 'enters wrong login data';
?>
数组 函数
array_multisort
参考使用:
/**
2. * 多维数组排序
3.* arrya_multisort()使用参考
4. */
5.$arr = array(
6. array('id'=>1,'data'=>'a'),
7. array('id'=>3,'data'=>'c'),
8. array('id'=>2,'data'=>'b'),
9. array('id'=>2,'data'=>'a')
10.);
11.$id = $data = array();
12.foreach($arr as $key => $value){
13. $id[$key] = $value['id'];
14. $data[$key] = $value['data'];
15.}
16.array_multisort($id, SORT_ASC, $data, SORT_DESC, $arr);
17.print_r($arr);
结果很显然:
1.Array
2.(
3.[0] => Array
4.(
5.[id] => 1
6.[data] => a
7.)
8.
9.[1] => Array
10.(
11.[id] => 2
12.[data] => b
13.)
14.
15.[2] => Array
16.(
17.[id] => 2
18.[data] => a
19.)
20.
21.[3] => Array
22.(
23.[id] => 3
24.[data] => c
25.)
26.
27.)
封装使用
//二维数组排序
function arraySequence($array,$field,$sort = 'SORT_ASC'){
$arrSort = array();
foreach($array as $uniqid => $row){
foreach($row as $key =>$value){
$arrSort[$key][$uniqid] = $value;
}
}
//constant()将变量值转换为常量
array_multisort($arrSort[$field],constant($sort),$array);
return $array;
}
ksort
对数组按照键名排序
public static function buildSign(Array $params)
{
if (isset($params['_sign'])) {
unset($params['_sign']);
}
$params = array_map_function($params, 'trim');
ksort($params);
$paramsStr = http_build_query($params);
$sign = sha1(md5($paramsStr).Config::get('api.app_secret'));
return $sign;
}
bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
对数组按照键名排序,保留键名到数据的关联。本函数主要用于关联数组。
- 参数
- array
输入的数组。 - sort_flags
可以用可选参数 sort_flags 改变排序的行为,可参考 sort()。
- 返回值
- 成功时返回 TRUE, 或者在失败时返回 FALSE。
范例:
Example #1 ksort() 例子
<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
以上例程会输出:
a = orange
b = banana
c = apple
d = lemon
array_unique
array_unique — 移除数组中重复的值
- 说明
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
array_unique() 接受 array 作为输入并返回没有重复值的新数组。
注意键名保留不变。array_unique() 先将值作为字符串排序,然后对每个值只保留第一个遇到的键名,接着忽略所有后面的键名。这并不意味着在未排序的 array 中同一个值的第一个出现的键名会被保留。
Note: 当且仅当 (string) $elem1 === (string) $elem2 时两个单元被认为相同。 例如,字符串表达一样时,会使用首个元素。
- 参数
- array
输入的数组。
2. sort_flags
第二个可选参数sort_flags 可用于修改排序行为:
排序类型标记:
SORT_REGULAR - 按照通常方法比较(不修改类型)
SORT_NUMERIC - 按照数字形式比较
SORT_STRING - 按照字符串形式比较
SORT_LOCALE_STRING - 根据当前的本地化设置,按照字符串比较。
- 返回值
返回过滤后的数组。
- 范例
Example #1 array_unique() 例子
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
以上例程会输出:
Array
(
[a] => green
[0] => red
[1] => blue
)
Example #2 array_unique() 和类型
<?php
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
?>
以上例程会输出:
array(2) {
[0] => int(4)
[2] => string(1) "3"
}
array_flip
array_flip 交换数组中的键和值
注意 array 中的值需要能够作为合法的键名(例如需要是 integer 或者 string)。如果类型不对,将出现一个警告,并且有问题的键/值对将不会出现在结果里。
如果同一个值出现多次,则最后一个键名将作为它的值,其它键会被丢弃。
用法:注意应用场景,通过两次反转去重
URL 函数
http_build_query
http_build_query — 生成 URL-encode 之后的请求字符串
string http_build_query ( mixed $query_data [, string $numeric_prefix [, string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )
使用给出的关联(或下标)数组生成一个经过 URL-encode 的请求字符串。
- 参数
- query_data
可以是数组或包含属性的对象。
一个 query_data 数组可以是简单的一维结构,也可以是由数组组成的数组(其依次可以包含其它数组)。
如果 query_data 是一个对象,只有 public 的属性会加入结果。
- numeric_prefix
如果在基础数组中使用了数字下标同时给出了该参数,此参数值将会作为基础数组中的数字下标元素的前缀。
这是为了让 PHP 或其它 CGI 程序在稍后对数据进行解码时获取合法的变量名。
- arg_separator
除非指定并使用了这个参数,否则会用 arg_separator.output 来分隔参数。
enc_type
默认使用 PHP_QUERY_RFC1738。
如果 enc_type 是 PHP_QUERY_RFC1738,则编码将会以 » RFC 1738 标准和 application/x-www-form-urlencoded 媒体类型进行编码,空格会被编码成加号(+)。
如果 enc_type 是 PHP_QUERY_RFC3986,将根据 » RFC 3986 编码,空格会被百分号编码(%20)。
- 返回值
- 返回一个 URL 编码后的字符串。
范例
Example #1 http_build_query() 使用示例
<?php
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo http_build_query($data) . "\n";
echo http_build_query($data, '', '&');
?>
以上例程会输出:
foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&baz=boom&cow=milk&php=hypertext+processor
Date/Time 函数
time()
返回当前的 Unix 时间戳
说明
int time ( void )
返回自从 Unix 纪元(格林威治时间 1970 年 1 月 1 日 00:00:00)到当前时间的秒数。
范例
Example #1 time() 例子
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60 secs
echo 'Now: '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>
以上例程的输出类似于:
Now: 2005-03-30
Next Week: 2005-04-06
Next Week: 2005-04-06
strtotime()
将任何字符串的日期时间描述解析为 Unix 时间戳
说明
int strtotime ( string $time [, int $now = time() ] )
本函数预期接受一个包含美国英语日期格式的字符串并尝试将其解析为 Unix 时间戳(自 January 1 1970 00:00:00 GMT 起的秒数),其值相对于 now 参数给出的时间,如果没有提供此参数则用系统当前时间。
参数
- time
日期/时间字符串。正确格式的说明详见 日期与时间格式。 - now
用来计算返回值的时间戳。
返回值
成功则返回时间戳,否则返回 FALSE。在 PHP 5.1.0 之前本函数在失败时返回 -1。
错误/异常
在每 次调用日期/时间函数时,如果时区无效则会引发 E_NOTICE 错误,如果使用系统设定值或 TZ 环境变量,则会引发 E_STRICT 或 E_WARNING 消息。参见 date_default_timezone_set()。
PCRE 函数
preg_match_all
执行一个全局正则表达式匹配
说明
int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )
搜索subject中所有匹配pattern给定正则表达式 的匹配结果并且将它们以flag指定顺序输出到matches中.
在第一个匹配找到后, 子序列继续从最后一次匹配位置搜索.
参数
-
pattern
要搜索的模式,字符串形式。
-
subject
输入字符串。
-
matches
多维数组,作为输出参数输出所有匹配结果, 数组排序通过flags指定。
-
flags
可以结合下面标记使用(注意不能同时使用PREG_PATTERN_ORDER和 PREG_SET_ORDER):
-
PREG_PATTERN_ORDER
结果排序为$matches[0]保存完整模式的所有匹配, $matches[1] 保存第一个子组的所有匹配,以此类推。
<?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
"<b>example: </b><div align=left>this is a test</div>",
$out, PREG_PATTERN_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>
以上例程会输出:
<b>example: </b>, <div align=left>this is a test</div>
example: , this is a test
因此, $out[0]是包含匹配完整模式的字符串的数组,
$out[1]是包含闭合标签内的字符串的数组。
如果正则表达式包含了带名称的子组,$matches 额外包含了带名称子组的键。
如果正则表达式里,子组名称重名了,则仅最右侧的自组储存在 $matches[NAME] 中。
<?php
preg_match_all(
'/(?J)(?<match>foo)|(?<match>bar)/',
'foo bar',
$matches,
PREG_PATTERN_ORDER
);
print_r($matches['match']);
?>
以上例程会输出:
Array
(
[0] =>
[1] => bar
)
-
PREG_SET_ORDER
结果排序为$matches[0]包含第一次匹配得到的所有匹配(包含子组), $matches[1]是包含第二次匹配到的所有匹配(包含子组)的数组,以此类推。
<?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
"<b>example: </b><div align=\"left\">this is a test</div>",
$out, PREG_SET_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>
以上例程会输出:
<b>example: </b>, example:
<div align="left">this is a test</div>, this is a test
-
PREG_OFFSET_CAPTURE
如果这个标记被传递,每个发现的匹配返回时会增加它相对目标字符串的偏移量。 注意这会改变matches中的每一个匹配结果字符串元素,使其 成为一个第0个元素为匹配结果字符串,第1个元素为 匹配结果字符串在subject中的偏移量。
<?php
preg_match_all('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
以上例程会输出:
Array
(
[0] => Array
(
[0] => Array
(
[0] => foobarbaz
[1] => 0
)
)
[1] => Array
(
[0] => Array
(
[0] => foo
[1] => 0
)
)
[2] => Array
(
[0] => Array
(
[0] => bar
[1] => 3
)
)
[3] => Array
(
[0] => Array
(
[0] => baz
[1] => 6
)
)
)
如果没有给定排序标记,假定设置为PREG_PATTERN_ORDER.
-
offset
通常, 查找时从目标字符串的开始位置开始。可选参数offset用于 从目标字符串中指定位置开始搜索(单位是字节)。
Note:
使用 offset 参数不同于传递 substr($subject, $offset) 的 结果到 preg_match_all() 作为目标字符串,因为 pattern 可以包含断言比如^, $ 或者 (?<=x) 。 示例查看 preg_match()。
返回值
返回完整匹配次数(可能是0),或者如果发生错误返回FALSE.
杂项函数
constant()
密码散列算法函数
password_hash
创建密码的哈希(hash)
string password_hash ( string $password , integer $algo [, array $options ] )
password_hash() 使用足够强度的单向散列算法创建密码的哈希(hash)。 password_hash() 兼容 crypt()。 所以, crypt() 创建的密码哈希也可用于 password_hash()。
当前支持的算法:
◦ PASSWORD_DEFAULT - 使用 bcrypt 算法 (PHP 5.5.0 默认)。 注意,该常量会随着 PHP 加入更新更高强度的算法而改变。 所以,使用此常量生成结果的长度将在未来有变化。 因此,数据库里储存结果的列可超过60个字符(最好是255个字符)。
◦ PASSWORD_BCRYPT - 使用 CRYPT_BLOWFISH 算法创建哈希。 这会产生兼容使用 "$2y$" 的 crypt()。 结果将会是 60 个字符的字符串, 或者在失败时返回 FALSE。
- 支持的选项:
◦ salt - 手动提供哈希密码的盐值(salt)。这将避免自动生成盐值(salt)。
省略此值后,password_hash() 会为每个密码哈希自动生成随机的盐值。这种操作是有意的模式。
Warning
盐值(salt)选项从 PHP 7.0.0 开始被废弃(deprecated)了。 现在最好选择简单的使用默认产生的盐值。
◦ cost - 代表算法使用的 cost。crypt() 页面上有 cost 值的例子。
省略时,默认值是 10。 这个 cost 是个不错的底线,但也许可以根据自己硬件的情况,加大这个值。
其他相关函数,示例:
//查看哈希值的相关信息
array password_get_info (string $hash)
//创建hash密码
string password_hash(string $password , integer $algo [, array $options ])
//判断hash密码是否特定选项、算法所创建
boolean password_needs_rehash (string $hash , integer $algo [, array $options ]
boolean password_verify (string $password , string $hash)
//验证密码
$password = 'password123456';//原始密码
$hash_password = password_hash($password, PASSWORD_BCRYPT);//使用BCRYPT算法加密密码
if (password_verify($password , $hash_password)){
echo "密码匹配";
}else{
echo "密码错误";
}