个人技术分享

字符串

is_string — 查找变量的类型是否是字符串

$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
    echo "is_string(";
    var_export($value);
    echo ") = ";
    echo var_dump(is_string($value));
}

/*
is_string(false) = bool(false)
is_string(true) = bool(false)
is_string(NULL) = bool(false)
is_string('abc') = bool(true)
is_string('23') = bool(true)
is_string(23) = bool(false)
is_string('23.5') = bool(true)
is_string(23.5) = bool(false)
is_string('') = bool(true)
is_string(' ') = bool(true)
is_string('0') = bool(true)
is_string(0) = bool(false)

*/

substr — 返回字符串的子串(截取字符串)

<?php
$rest = substr("abcdef", -1);    // 返回 "f"
$rest = substr("abcdef", -2);    // 返回 "ef"
$rest = substr("abcdef", -3, 1); // 返回 "d"

$rest = substr("abcdef", 0, -1);  // 返回 "abcde"
$rest = substr("abcdef", 2, -1);  // 返回 "cde"
$rest = substr("abcdef", 4, -4);  // 返回 ""; 在 PHP 8.0.0 之前,返回 false
$rest = substr("abcdef", -3, -1); // 返回 "de"

echo substr('abcdef', 1);     // bcdef
echo substr("abcdef", 1, null); // bcdef; 在 PHP 8.0.0 之前,返回空字符串
echo substr('abcdef', 1, 3);  // bcd
echo substr('abcdef', 0, 4);  // abcd
echo substr('abcdef', 0, 8);  // abcdef
echo substr('abcdef', -1, 1); // f

// 访问字符串中的单个字符
// 也可以使用中括号
$string = 'abcdef';
echo $string[0];                 // a
echo $string[3];                 // d
echo $string[strlen($string)-1]; // f
?>

strlen — 获取字符串长度

<?php
$str = 'abcdef';
echo strlen($str); // 6

$str = ' ab cd ';
echo strlen($str); // 7
//strlen() 返回的是字符串的字节数,而不是其中字符的数量。
?>

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

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


// 忽视位置偏移量之前的字符进行查找
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, 不是 0
echo $pos; //7

str_replace — 子字符串替换

$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
echo $bodytag; //<body text='black'>

$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
echo $onlyconsonants; //Hll Wrld f PHP

$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");
$newphrase = str_replace($healthy, $yummy, $phrase);
echo $newphrase; //You should eat pizza, beer, and ice cream every day.

$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count;//2

$str     = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order   = array("\r\n", "\n", "\r");
$replace = '<br />';
$newstr = str_replace($order, $replace, $str);
echo $newstr;//Line 1<br />Line 2<br />Line 3<br />Line 4<br />

// 输出 F ,因为 A 被 B 替换,B 又被 C 替换,以此类推...
// 由于从左到右依次替换,最终 E 被 F 替换
$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);//F

$letters = array('a', 'p');
$fruit   = array('apple', 'pear');
$text    = 'a p';
$output  = str_replace($letters, $fruit, $text);
echo $output; //apearpearle pear

sprintf — 返回格式化字符串

<?php
$num = 5;
$location = 'tree';

$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location); //There are 5 monkeys in the tree

?>

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

$text   = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = trim($text);
var_dump($trimmed);

$trimmed = trim($text, " \t.");
var_dump($trimmed);

$trimmed = trim($hello, "Hdle");
var_dump($trimmed);

// 清除 $binary 首位的 ASCII 控制字符
// (包括 0-31)
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);

/*
string(32) "		These are a few words :) ...  "
string(16) "	Example string
"
string(11) "Hello World"

string(28) "These are a few words :) ..."
string(24) "These are a few words :)"
string(5) "o Wor"
string(14) "Example string"
*/

rtrim — 删除字符串末端的空白字符(或者其他字符)

<?php

$text = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = rtrim($text);
var_dump($trimmed);

$trimmed = rtrim($text, " \t.");
var_dump($trimmed);

$trimmed = rtrim($hello, "Hdle");
var_dump($trimmed);

// 删除 $binary 末端的 ASCII 码控制字符
// (包括 0 - 31)
$clean = rtrim($binary, "\x00..\x1F");
var_dump($clean);

?>

/*
string(32) "		These are a few words :) ...  "
string(16) "	Example string
"
string(11) "Hello World"

string(30) "		These are a few words :) ..."
string(26) "		These are a few words :)"
string(9) "Hello Wor"
string(15) "	Example string"

*/

strtolower — 将字符串转化为小写

<?php
$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
?>

strtoupper — 将字符串转化为大写

<?php
$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
?>

md5 — 计算字符串的 MD5 散列值

<?php
$str = 'apple';

if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
    echo "Would you like a green or red apple?";
}
?>

数组

count — 统计数组、Countable 对象中所有元素的数量

<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
var_dump(count($a));//int(3)
$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
var_dump(count($b));//int(3)
?>
<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', 'pea'));
// 递归计数
var_dump(count($food, COUNT_RECURSIVE)); //int(8)
// 常规计数
var_dump(count($food)); //int(2)
?>

explode — 使用一个字符串分割另一个字符串(字符串转数组)

<?php
// 示例 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

// 示例 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *

/*
  字符串内不包含分隔字符时,
  会简单返回只有一个原始字符串元素的 array。
*/
$input1 = "hello";
$input2 = "hello,there";
$input3 = ',';
var_dump( explode( ',', $input1 ) );
var_dump( explode( ',', $input2 ) );
var_dump( explode( ',', $input3 ) );



$str = 'one|two|three|four';

// 正数的 limit
print_r(explode('|', $str, 1)); //Array([0] => one|two|three|four)
print_r(explode('|', $str, 2)); //Array([0] => one [1] => two|three|four)

// 负数的 limit
print_r(explode('|', $str, -1)); //Array([0] => one [1] => two [2] => three)
print_r(explode('|', $str, -2)); //Array([0] => one [1] => two)
?>

implode — 用字符串连接数组元素(数组转字符串)

<?php

$array = ['lastname', 'email', 'phone'];
var_dump(implode(",", $array)); // string(20) "lastname,email,phone"

// Empty string when using an empty array:
var_dump(implode('hello', [])); // string(0) ""

// The separator is optional:
var_dump(implode(['a', 'b', 'c'])); // string(3) "abc"


$elements = array('a', 'b', 'c');
echo "<ul><li>" . implode("</li><li>", $elements) . "</li></ul>"; //<ul><li>a</li><li>b</li><li>c</li></ul>


?>

is_array — 检测变量是否是数组

<?php
$yes = ['this', 'is', 'an array'];
echo is_array($yes) ? 'Array' : 'not an Array';
echo "\n";
$no = 'this is a string';
echo is_array($no) ? 'Array' : 'not an Array';
?>

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


<?php
$os = array("Mac", "NT", "Irix", "Linux");
//区分大小写例子
if (in_array("Irix", $os)) {
    echo "Got Irix"; //Got Irix
}
if (in_array("mac", $os)) {
    echo "Got mac"; 
}
//严格类型检查例子
$a = array('1.10', 12.4, 1.13);
if (in_array('12.4', $a, true)) {
    echo "'12.4' found with strict check\n";
}

if (in_array(1.13, $a, true)) {
    echo "1.13 found with strict check\n"; //1.13 found with strict check
}
//数组
$a = [['p', 'h'], ['p', 'r'], 'o'];
if (in_array(['p', 'h'], $a)) {
    echo "'ph' was found\n"; //'ph' was found
}
if (in_array(['f', 'i'], $a)) {
    echo "'fi' was found\n";
}
if (in_array('o', $a)) {
    echo "'o' was found\n"; //'o' was found
}
?>

array_key_exists — 检查数组里是否有指定的键名或索引

$search_array = ['first' => 1, 'second' => 4];
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array"; //The 'first' element is in the array
}

isset — 检测变量是否已声明并且其值不为 null

<?php

$var = '';

// 结果为 TRUE,所以后边的文本将被打印出来。
if (isset($var)) {
    echo "This var is set so I will print."; //This var is set so I will print.

}

$a = "test";
$b = "anothertest";

var_dump(isset($a));      // TRUE
var_dump(isset($a, $b)); // TRUE

unset ($a); //unset — 清除指定变量

var_dump(isset($a));     // FALSE
var_dump(isset($a, $b)); // FALSE

$foo = NULL;
var_dump(isset($foo));   // FALSE

?>
array_key_exists() 与 isset() 的对比

isset() 对于数组中为 null 的值不会返回 true,而 array_key_exists() 会。

<?php
$search_array = array('first' => null, 'second' => 4);
// 返回 true
array_key_exists('first', $search_array); //true
// 返回 false
isset($search_array['first']); //false
?>

array_column — 返回输入数组中指定列的值

// 表示从数据库返回的记录集的数组
$records = [
    [
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ],
    [
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ],
    [
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ],
    [
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    ]
);
 
$first_names = array_column($records, 'first_name');
print_r($first_names); /*Array(
 [0] => John
 [1] => Sally
 [2] => Jane 
 [3] => Peter                                                                                                                                                                                                                                                                                                                                      )*/
//从结果集中总取出 last_name 列,用相应的“id”作为键值
// 使用示例 #1 中的 $records 数组
$last_names = array_column($records, 'last_name', 'id');
print_r($last_names); /*Array
(
    [2135] => Doe
    [3245] => Smith
    [5342] => Jones
    [5623] => Doe
)*/

$first_names = array_column($records, null, 'id');
print_r($last_names); /*Array
(
    [2135] => Array
        (
            [id] => 2135
            [first_name] => John
            [last_name] => Doe
        )

    [3245] => Array
        (
            [id] => 3245
            [first_name] => Sally
            [last_name] => Smith
        )

    [5342] => Array
        (
            [id] => 5342
            [first_name] => Jane
            [last_name] => Jones
        )

    [5623] => Array
        (
            [id] => 5623
            [first_name] => Peter
            [last_name] => Doe
        )

)*/

array_keys — 返回数组中所有的键

$array = array("size" => "XL", "color" => "gold");
var_dump(array_keys($array)) //['size','color']

array_values — 返回数组中所有的值

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

array_filter — 使用回调函数过滤数组的元素

<?php
function odd($var)
{
    // 返回输入整数是否为奇数(单数)
    return $var & 1;
}
function even($var)
{
    // 返回输入整数是否为偶数
    return !($var & 1);
}
$array1 = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
$array2 = [6, 7, 8, 9, 10, 11, 12];
echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));

$array3 = [1,'0', 0, false, null, '','fasle'];
print_r(array_filter($array3)); //[1, false]
?>

array_merge — 合并一个或多个数组

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result); /*
Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)
*/

//如果你想完全保留原有数组并只想新的数组附加到后面,可以使用 + 运算符:
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);/*
array(5) {
  [0]=>
  string(6) "zero_a"
  [2]=>
  string(5) "two_a"
  [3]=>
  string(7) "three_a"
  [1]=>
  string(5) "one_b"
  [4]=>
  string(6) "four_b"
}
*/
?>

array_slice — 从数组中取出一段

$input = array("a", "b", "c", "d", "e");

print_r(array_slice($input, 2));      // [c,d,e]
print_r(array_slice($input, -2, 1));  // [d]
print_r(array_slice($input, 0, 3));   // [a,b,c]

// 注意数组中 key 的不同
print_r(array_slice($input, 2, -1)); // [c,d]
print_r(array_slice($input, 2, -1, true)); // [c,d]

$ar = array('a'=>'apple', 'b'=>'banana', '42'=>'pear', 'd'=>'orange');
print_r(array_slice($ar, 0, 3));/*
Array
(
    [a] => apple
    [b] => banana
    [0] => pear
)
*/
print_r(array_slice($ar, 0, 3, true));/*
Array
(
    [a] => apple
    [b] => banana
    [42] => pear
)
*/

array_map — 为数组的每个元素应用回调函数


<?php
function cube($n)
{
    return ($n * $n * $n);
}

$a = [1, 2, 3, 4, 5];
$b = array_map('cube', $a);
print_r($b); /*
Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)
*/
?>

array_shift — 将数组开头的单元移出数组

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack); /*Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)*/
?>

array_pop — 弹出数组最后一个单元(出栈)

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack); /* Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)*/
?>

函数处理

unset — 清除指定变量

<?php
function destroy_foo() 
{
    global $foo;
    unset($foo);
}

$foo = 'bar';
destroy_foo();
echo $foo; //bar
?>

empty — 检查变量是否为空

<?php
$var = 0;

// 因为 $var 为空,所以计算结果为 true
if (empty($var)) {
    echo '$var is either 0, empty, or not set at all';
}

// 因为 $var 已赋值,所以计算结果为 true
if (isset($var)) {
    echo '$var is set even though it is empty';
}
?>

function_exists — 如果给定的函数已经被定义就返回 true

<?php
if (function_exists('imap_open')) {
    echo "IMAP functions are available.<br />\n";
} else {
    echo "IMAP functions are not available.<br />\n";
}
?>

is_null — 检测变量是否是 null

<?php

error_reporting(E_ALL);

$foo = NULL;
var_dump(is_null($inexistent), is_null($foo));
/*
Notice: Undefined variable: inexistent in /box/script.php on line 6
bool(true)
bool(true)
*/
?>

method_exists — 检查类的方法是否存在

<?php
$directory = new Directory('.');
var_dump(method_exists($directory,'read')); //bool(true)
?>

<?php
var_dump(method_exists('Directory','read')); //bool(true)
?>

Date/Time 函数

time — 返回当前的 Unix 时间戳

<?php
echo 'Now: '. time(); //Now: 1660338149
?>

microtime — 返回当前 Unix 时间戳和微秒数

<?php
$time_start = microtime(true);

// Sleep 一会
usleep(100);

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";//Did nothing in 0.00052189826965332 seconds
?>

date — 格式化 Unix 时间戳


$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
$today = date("H:i:s");                         // 17:16:18
$today = date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18(MySQL DATETIME 格式)

JSON函数

json_encode — 对变量进行 JSON 编码

<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo json_encode($arr); //{"a":1,"b":2,"c":3,"d":4,"e":5}
?>

json_decode — 对 JSON 格式的字符串进行解码

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

/*
object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
*/

<?php

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345

?>
?>