php 中常用的函数


php 中其他常用的函数


1 时间

  • 时间格式化:

    date(“Y-m-d H:i:s”,time()); //2015-02-06 15:27:31 date(“Y-n-j H:i:s”,time()); //2015-2-6 15:27:31

  • 将时间转为long类型时间戳:

    $date = strtotime(“2014-11-02 08:36:51”);

  • 将[2015-02-06 15:27:31]转为[2015年02月06日 15时27分31秒]类型:

    function myFormatDate($date){ $date = strtotime($date); $a=date(“Y”,$date); $b=date(“m”,$date); $c=date(“d”,$date); $d=date(“H”,$date); $e=date(“i”,$date); $f=date(“s”,$date); return $a.’年’.$b.’月’.$c.’日 ‘.$d.’时’.$e.’分’.$f.’秒’; }

2 将数组转为字符串:

$arr = array('Hello','World!','I','love','Shanghai!');
echo implode(",",$arr) ;    //Hello,World!,I,love,Shanghai!

3.把&,”,’,<,>转换为html实体:

$line ="This is some <b>bold</b> text.";
echo htmlspecialchars($line);    //This is some <b>bold</b> text.

4.字符串的字符编码转换:

$text = "This is the Euro symbol '€'.";
iconv("UTF-8", "ISO-8859-1", $text);

5.JSON数据方法:(具体用法请参考PHP数组中的JSON解析)

json_decode — 将JSON格式转为数组或者对象。
json_encode — 将数组或者对象转为JSON格式。


php 中 字符串常用的函数


1 cho — 输出字符串:

echo 'hello';

2.strpos — 查找字符串首次出现的位置:

$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring,$findme);

// 注意这里使用的是 ===。因为 'a' 是第 0 位置上的(第一个)字符。
if ($pos === false) {
    echo "not found";
}

3.strlen — 获取字符串长度:

$str = 'abcdef';
echo strlen($str);    // 6
mb_strlen — 获取字符串长度(一个中文算一个长度):
$str='PHP脚本之家good'; 
echo mb_strlen($str,'utf-8');  //假定此代码所在php文件的编码为utf-8.结果:11

4.substr — 返回字符串的子串:

echo substr('abcdef',1);      // bcdef
echo substr('abcdef', 1,3);   // bcd
echo substr('abcdef', 0, 4);   // abcd
mb_substr— 中文截取, 返回字符串的子串:
$str='PHP脚本之家good'; 
echo mb_substr($str,0,5,'utf-8'); //截取头5个字,假定此代码所在php文件的编码为utf-8.  结果:PHP脚本

5.trim — 去除字符串首尾处的空白字符(或者其他字符):

$text   = " These are a few words   ";
echo trim($text);  //These are a few words

6.explode — 使用一个字符串分割另一个字符串:

$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ",$pizza);
echo $pieces[0];     // piece1
echo $pieces[1];     // piece2
<?php
$email = 'phpddt1990@163.com';
$arr = split('\.|@',$email);
print_r($arr);  //Array ( [0] => phpddt1990 [1] => 163 [2] => com )
?>
注:explode()没有使用正则表达式,而split()使用正则表达式.(在explode中"."不用转意,而在split中"."需要转意\.)

7.implode — 将一个一维数组的值转化为字符串:

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated;     // lastname,email,phone

8.substr_count — 计算字串出现的次数:

$text = 'This is a test';
echo strlen($text); // 14
echo substr_count($text, 'is');   // 2

9.substr_replace — 替换字符串的子串:

echo substr_replace("Hello world","Shanghai",6);   //从字符串的第6个位置开始替换(把"world"替换成"Shanghai")

10.number_format — 以千位分隔符方式格式化一个数字:

$number = 1234.563;
echo number_format($number,2);    //1,234.56

11.str_replace — 子字符串替换:

echo str_replace("world","Shanghai","Hello world!");    //Hello Shanghai!

12.str_repeat — 重复一个字符串:

echo str_repeat("-=", 10);  //-=-=-=-=-=-=-=-=-=-=

13.strtolower — 将字符串转化为小写:

$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtolower($str);
echo $str;     // mary had a little lamb and she loved it so

14.lcfirst — 使一个字符串的第一个字符小写:

$foo = 'HelloWorld';
$foo = lcfirst($foo);         // helloWorld

15.strtoupper — 将字符串转化为大写:

$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtoupper($str);
echo $str; // 打印 MARY HAD A LITTLE LAMB AND SHE LOVED IT SO

16.ucwords — 将字符串中每个单词的首字母转换为大写:

$foo = 'hello world!';
$foo = ucwords($foo);             // Hello World!

17.substr_compare — 二进制安全比较字符串(从偏移位置比较指定长度):

echo substr_compare("Hello world","world",6);    //比较两个字符串,从第一个参数的第6位开始开始比较

18.str_split — 将字符串转换为数组:

$str = "Hello Friend";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

print_r($arr1);
print_r($arr2);
Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] =>
    [6] => F
    [7] => r
    [8] => i
    [9] => e
    [10] => n
    [11] => d
)

Array
(
    [0] => Hel
    [1] => lo
    [2] => Fri
    [3] => end
)


数组常用的函数


1.数组输出:

foreach($change as $k => $v){
       echo "<br/>".$k."----".$v;
 }

2.常用函数:

1). count($arr):可以统计该数组共有多少元素.

2). is_array($arr):判断是否是一个数组.

3). print_r($arr) 和 var_dump($arr):打印数组信息.

4). explode($str):对字符串进行分割,结果为数组.

$str="北京&张三&天津&宋江&林冲";

$arr=explode("&",$str);

print_r($arr);

3.array — 新建一个数组:

$fruits = array (
    "fruits"  => array("a" => "orange", "b" => "banana", "c" => "apple"),
    "numbers" => array(1, 2, 3, 4, 5, 6),
    "holes"   => array("first", 5 => "second", "third")
);
$array = array(1, 1, 1, 1, 1, 8 => 1,  4 => 1, 19, 3 => 13);

4.array_merge — 合并一个或多个数组:

$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
Array
    (
        [0] => foo
        [1] => bar
    )

5.count — 计算数组中的单元数目或对象中的属性个数:

$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
$result = count($b);
// $result == 3

6.array_count_values — 统计数组中所有的值出现的次数:

$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

7.array_search — 在数组中搜索给定的值,如果成功则返回相应的键名:

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;

8.array_key_exists — 检查给定的键名或索引是否存在于数组中:

$search_array = array('first' => 1, 'second' => 4);
array_key_exists('first', $search_array);   //true

9.in_array — 检查数组中是否存在某个值:

$os = array("Mac", "NT", "Irix", "Linux");
echo in_array("Irix", $os); //true
echo in_array("mac", $os); //false ,区分大小写

10.sort — 对数组排序:

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange

11.ksort — 对数组按照键名排序:

$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

12.asort — 对数组进行排序并保持索引关系:

$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
c = apple
b = banana
d = lemon
a = orange

13.array_values — 返回数组中所有的值:

$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
Array
(
    [0] => XL
    [1] => gold
)

14.array_keys — 返回数组中部分的或所有的键名:

$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
Array
(
    [0] => 0
    [1] => color
)
$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)

15.array_sum — 计算数组中所有值的和:

$a = array(2, 4, 6, 8);
echo array_sum($a);  //20
$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo array_sum($b);  //6.9

16.end — 将数组的内部指针指向最后一个单元:

$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry

17.next — 将数组中的内部指针向前移动一位:

$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = next($transport);    // $mode = 'car';
$mode = prev($transport);    // $mode = 'bike';
$mode = end($transport);     // $mode = 'plane';

18.array_unique — 移除数组中重复的值:

$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
Array
(
    [a] => green
    [0] => red
    [1] => blue
)
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

19.array_replace — 使用传递的数组替换第一个数组的元素:

$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$basket = array_replace($base, $replacements);
print_r($basket);
Array
(
    [0] => pineapple
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)

20.array_diff — 计算数组的差集:

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result=array_diff($a1,$a2);
Array ( [d] => yellow )

21.array_intersect — 计算数组的交集:

$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
Array
(
    [a] => green
    [0] => red
)

22.array_filter — 用回调函数过滤数组中的单元,可以用来过滤空元素:

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);
print_r(array_filter($array1, "odd"));
print_r(array_filter($array2, "even"));
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)
$array3 = array("a"=>"foo", "b"=>false, "c"=>-1, "d"=>null, "e"=>'');
print_r(array_filter($array3));
Array
(
    [a] => foo
    [c] => -1
)


数学相关的函数Math函数


1.abs — 绝对值:

$abs = abs(-4.2);     // $abs = 4.2; (double/float)
$abs2 = abs(5);       // $abs2 = 5; (integer)

2.ceil — 进一法取整:

echo ceil(4.3);      // 5
echo ceil(9.999);  // 10
echo ceil(-3.14);   // -3

3.floor — 舍去法取整:

echo floor(4.3);       // 4
echo floor(9.999);   // 9
echo floor(-3.14);   // -4

4.max — 找出最大值:

echo max(1, 3, 5, 6, 7);       // 7
echo max(array(2, 4, 5));    // 5

5.min — 找出最小值:

echo min(2, 3, 1, 6, 7);      // 1
echo min(array(2, 4, 5));   // 2

6.rand — 产生一个随机整数:

echo rand(5, 15);   //5到15之间的随机数

7.round — 对浮点数进行四舍五入:

echo round(3.4);            // 3
echo round(3.5);            // 4
echo round(5.045, 2);    // 5.05
echo round(5.055, 2);    // 5.06

8.bindec — 二进制转换为十进制:

echo bindec('110011');          //51
echo bindec('000110011');    //51

9.decbin — 十进制转换为二进制:

echo decbin(12);      //1100
echo decbin(26);      //11010

10.fmod — 返回除法的浮点数余数:

$x = 5.7;
$y = 1.3;
$r = fmod($x, $y);
// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7

11.pi — 得到圆周率值:

echo pi();      // 3.1415926535898
echo M_PI;    // 3.1415926535898

12.pow — 指数表达式:

var_dump(pow(2, 8));      // int(256)


文件操作相关的函数


1.basename — 返回路径中的文件名部分:

echo basename("/etc/sudoers.d", ".d");  //sudoers
echo basename("/etc/passwd");  //passwd

2.dirname — 返回路径中的目录部分:

echo dirname("/etc/passwd");  //etc

3.rmdir — 删除目录,该目录必须是空的:

rmdir('examples');
unlink('test.html');

5.rename — 重命名一个文件或目录:

rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");

6.pathinfo — 返回文件路径的信息:

$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
echo $path_parts['dirname'];  //  /www/htdocs/inc
echo $path_parts['basename'];  //  lib.inc.php
echo $path_parts['extension'];  //  php
echo $path_parts['filename'];   //  lib.inc

7.filesize — 取得文件大小:

$filename = 'somefile.txt';
echo filesize($filename);

8.filetype — 取得文件类型:

$filename = 'somefile.txt';
echo filetype($filename);  // txt
echo filetype('/etc/');        // dir

9.fopen — 打开文件或者 URL:

$handle = fopen("/home/rasmus/file.txt", "r");

10.fread — 读取文件(可安全用于二进制文件):

$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);

11.fwrite — 写入文件(可安全用于二进制文件):

$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);  //123

12.fclose — 关闭一个已打开的文件指针:

$handle = fopen('somefile.txt', 'r');
fclose($handle);

13.feof — 测试文件指针是否到了文件结束的位置:

while (!feof($file)) {
}

14.file_exists — 检查文件或目录是否存在:

$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
    echo "The file $filename exists";
}

15.is_dir — 判断给定文件名是否是一个目录:

echo is_dir('a_file.txt');

16.mkdir — 新建目录:

mkdir("/path/to/my/dir", 0700);

17.is_file — 判断给定文件名是否为一个正常的文件:

echo is_file('a_file.txt');

18.is_uploaded_file — 判断文件是否是通过 HTTP POST 上传的:

if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
   echo "File uploaded successfully.";
}

19.move_uploaded_file — 将上传的文件移动到新位置:

$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}

20.copy — 拷贝文件:

$file = 'example.txt';
$newfile = 'example.txt.bak';

if (!copy($file, $newfile)) {
    echo "failed to copy $file...\n";
}

21.file_get_contents — 将整个文件读入一个字符串:

$homepage = file_get_contents('http://www.baidu.com/');
echo $homepage;  //将会把百度输出来
curl— 可以模拟GET、POST等HTTP请求。功能比file_get_contents 强大,效率比file_get_contents 高四倍。

22.file_put_contents — 将一个字符串写入文件:

$file = 'people.txt';
$current = file_put_contents($file,"hello world!");

23.file — 把整个文件读入一个数组中:

// 将一个文件读入数组。本例中通过 HTTP 从 URL 中取得 HTML 源文件。
$lines = file('http://www.example.com/');
// 将一个文件输出。本例中通过 HTTP 从 URL 中取得 HTML 源文件。
$strs = readfile('http://www.example.com/');
echo $strs;

24.parse_ini_file — 解析一个配置文件:

$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);

25.获取文件时间:

fileatime — 取得文件的上次访问时间
filectime — 取得文件的上次权限修改时间
filemtime — 取得文件的上次内容修改时间

$filename = 'somefile.txt';
echo date("Y-m-d H:i:s", fileatime($filename));
echo date("Y-m-d H:i:s", filectime($filename));
echo date("Y-m-d H:i:s", filemtime($filename));

26.realpath — 返回规范化的绝对路径名:

echo realpath('/windows/system32');  //C:\WINDOWS\System32

27.stat — 给出文件的信息:

$stat = stat('C:\php\php.exe');
var_dump($stat);

28.disk_total_space — 返回一个目录的磁盘总大小:

// $df 包含 "/" 目录的磁盘大小
$ds = disk_total_space("/");
//在 Windows 下:
$ds = disk_total_space("C:");

29.disk_free_space — 返回目录中的可用空间:

//在 Windows 下:
$df_c = disk_free_space("C:");
// $df 包含根目录下可用的字节数
$df = disk_free_space("/");
Buy me a 肥仔水!