所有缺失的PHP函数

0.0.65 2018-11-30 12:55 UTC

This package is auto-updated.

Last update: 2024-09-29 04:43:20 UTC


README

只需运行 composer install [package_name]

之后,所有这些函数都应在每个PHP文件中可用(通过composer的自动加载器)

数组相关

字符串相关

文件相关

互联网相关

数组相关函数

where

返回匹配特定键值条件的数据

function where(array $array = [], array $cond = [])

示例

$match = where([['a'=>1],['b'=>2]], ['b'=>2]);

randomize

返回数组的随机版本(原始数组不变)

function randomize(array $array)

pluck

返回多维数组中所有项的相同键

function pluck(array $array, string $match)

not_empty

非空的相反。如果非空,则返回$value,否则返回false。非常适合if循环。如果哈希表的所有值都为空,则也返回false。

function not_empty($value)

示例

$v = not_empty([]); // returns false
$v = not_empty(['a'=>'','b'=>'']); // returns false
$v = not_empty([1,2]); // returns [1,2]

array_map_key_values

类似于array map,但可以更改键和值(原始数组不变)

function array_map_key_values($closure, $arr)

示例

$v = array_map_key_values(function (&$k, &$v) { $k = "$k-a"; $v = "$v-3"; }, ['a' => 1, 'b' => 2, 'c' => 3]);

array_map_args

使用args调用array_map函数

function array_map_args($fn, $array, ...$args)

示例

$trim = array_map_args('ltrim', ['/test', '/best'], '/'); //passes '/' to ltrim

sort_by_key

按任何键对数组进行排序

function sort_by_key($arr, $key, $descending = FALSE)

示例

$v = sort_by_key([['name' => 'moe',   'age' => 40],['name' => 'larry', 'age' => 50],['name' => 'curly', 'age' => 60]], 'age', true);

group_by

按任何键对数组项进行分组

function group_by($arr, $match)

示例

$v = group_by([['name' => 'maciej',    'continent' => 'Europe'],['name' => 'yoan',      'continent' => 'Europe'],['name' => 'brandtley', 'continent' => 'North America']], 'continent');

chunk

将数组拆分为块

// → [[1, 2, 3], [4, 5]]

function chunk(array $array, $size = 1, $preserveKeys = FALSE)

示例

$v = chunk([1, 2, 3, 4, 5], 3);

array_set

使用点.path表示法设置数组项

function array_set(array &$arr, $path, $val)

示例

$arr = []; array_set($arr, 'a.b.c.d', 11);

array_get

使用点.path表示法获取数组项

function array_get(array $arr, $path, $default = NULL)

示例

$v = array_get($arr, 'a.b.c.d', 'default');

json_decode_array

将字符串、对象或stdClass转换为数组($preserve = true,否则保留空对象"{}"为stdClass,否则转换为"[]")

function json_decode_array($obj, $preserve = TRUE)

has_keys

检查数组中是否存在所有键(并且不为空)

返回值是只包含键的哈希表

function has_keys($hash, ...$keys)

pluck_keys

从哈希表中返回所选键(包括空键)

function pluck_keys($hash, ...$keys)

array_flatten

将多维数组展平

function array_flatten(array $array)

pluck_keys_ignore_empty

只从哈希中返回所选键(忽略空值)

function pluck_keys_ignore_empty($hash, ...$keys)

is_hash

检查数组是否为关联数组

function is_hash(array $arr)

is_email

检查字符串是否为电子邮件地址(如果为真则返回 $email,否则返回 false)

function is_email($email)

is_phone

检查字符串是否为电话号码(如果为真则返回 $phone,否则返回 false)

function is_phone($phone)

is_url

检查字符串是否为 URL(如果为真则返回 $url,否则返回 false)

function is_url($url)

array_first

获取数组或哈希的第一个元素

@return array|string

function array_first($array, $reverse = FALSE)

示例

$first = array_first([1,2,3]) => 1;

array_last

获取数组或哈希的最后一个元素

function array_last($array)

示例

$last = array_first([1,2,3], true) => 3;

array_filter_regex

通过正则表达式过滤所有数组元素

function array_filter_regex($regex, $array)

示例

$php = array_filter_regex('/\.php$/', $files);

array_except

从数组中删除所选项/或从哈希中删除键

function array_except(array $arr, ...$args)

in_array_nc

不区分大小写的 in_array 函数

function in_array_nc($needle, $haystack)

字符串相关函数

lines

将字符串拆分为数组

function lines($str, $delim = '\r?\n')

示例

$lines = lines("this\nis\n\na\r\ntest");

single_line

将多行文本转换为单行

function single_line($text, $delim = '')

示例

$merge = single_line("this\nis\n\na\ntest", " - ");

ansi

从字符串中删除非 ANSI 字符

function ansi($str)

slugify

创建单词或短语的 slug 版本

function slugify($text, $unique = FALSE)

示例

$unique = slugify('this is a test', true = adds a number or increments existing number);

password

生成随机密码

function password($length = 16)

str_insert

在现有字符串中匹配短语后插入字符串

function str_insert($document, $match, $insert, $ignore_case = FALSE, $replace = FALSE)

str_replace_block

用现有字符串替换匹配标签之间的块

function str_replace_block($document, $match_start, $match_end, $insert, $ignore_case = FALSE, $replace = FALSE)

示例

$out = str_replace_block('data', '// ** start', '// ** end', 'new content', false, false);

str_wrap

将字符串包裹在字符中(如果字符串为空则返回 '')- 自动确定正确的字符为 NULL

function str_wrap($input, $left, $right = NULL, $wrap_blank = FALSE)

示例

$str = str_wrap('test', "<", ">", true); => <test>, $str = str_wrap('ok', '"'); => "ok", $str = str_wrap('', '<b>'); => ''

str_quote

给字符串(或数组的项)加引号

function str_quote($input, $char = '"', $trim = TRUE)

示例

$arr = str_quote([1, 'one ', '"two"']); //["1", "one", "two"]

str_match_all_words

如果字符串包含所有单词则返回 true

function str_match_all_words($str, array $words, $whole_words = TRUE, $ignore_case = TRUE, $order = FALSE)

示例

$match = str_match_all_words('this is a test', ['/Th.s/i', 'a', 'test'], true, true, true); //order = words must be in order. Note: 1st word is regex, 2nd is a whole word.

str_match_brackets

返回字符串中所有平衡匹配的括号

function str_match_brackets($str, $bracket = '

next_version

将版本号增加 1

function next_version($version)

kebab

将任何单词转换为 kebab-case

function kebab($input, $delim = '-')

camel

将任何单词转换为 camelCase

function camel($string)

unslugify

将 camel/kebab/下划线格式的文本转换为正常文本

function unslugify($slug, $ucwords = FALSE)

remove_parens

从字符串中返回括号内的任何文本

function remove_parens($string)

示例

$str = remove_parens("Hustlin' ((Remix) Album Version (Explicit)) with (a(bbb(ccc)b)a) speed!");

template

替换模板中的任何标签

function template($str, $tags = [], $ignore_missing = FALSE)

示例

$out = template('hi {{first}}, today is {{date}}', ['first' => 'san', 'date' => today()]);

file_template

与模板相同,但使用文件而不是字符串

function file_template($path, $tags = [])

bool

将字符串值转换为等效的布尔值

function bool($str)

eval_php

评估 PHP 字符串,类似于 include_once

function eval_php($code, $vars = [])

示例

$result = eval_php('Hi <?php echo 1; ?>!', get_defined_vars()); //Hi 1!

words

将句子分为三个单词

function words($text)

示例

$v = words('this is mr.san "hello" there!');

sentences

将段落拆分为句子

function sentences($str)

示例

$v = sentences('this is a test. hello dr.dre, how are you? ok, bye.');

split_name

将姓名拆分为首字母和姓氏

function split_name($name, $default = 'Member')

stop_words

列出最常见的英文停用词

function stop_words()

extract_email

从文本中提取电子邮件地址

function extract_email($text, $single = TRUE)

email_format

将姓名、电子邮件转换为 "name"

function email_format($email, $name = '')

html2text

将 HTML 转换为文本

function html2text($html, $extract_links = TRUE)

cookie_get_json

获取 cookie 值或使用 JSON 格式返回 $default

function cookie_get_json($name, $default = [])

cookie_set_json

使用 JSON 格式在浏览器中设置 cookie

function cookie_set_json($name, $value, $expires = '+1 day', $append = FALSE, $domain = '')

self_uri

返回(净化后的)当前页面的 URL

function self_uri($params = FALSE)

absolute_uri

如果 uri 中尚未包含 http 部分,则追加 http 部分

function absolute_uri($path, $host = '')

url_append_params

在现有 URL 的末尾追加新参数

function url_append_params($url, $params = [])

file_name

返回没有扩展名的文件名

function file_name($path)

示例

$name = file_name('c:/test.jpg'); //test

file_ext

返回文件扩展名(不带点)

function file_ext($path)

示例

$ext = file_name('c:/test.jpg'); //jpg

change_ext

更改文件扩展名(可选路径)

function change_ext($path, $new_ext, $new_path = '')

示例

$path = change_ext('c:/d/tmp.txt', 'mp3', [new_path]); # c:/d/tmp.mp3

file_arr

将文件读入数组

function file_arr($path)

示例

$arr = file_arr('some.txt');

文件相关函数

read_csv

读取包含标题的 CSV 文件

function read_csv($path, $header = FALSE, $delim = ',')

示例

$arr = read_csv('file', ['col1', 'col2'] | true = first line is header | false = no header);

read_json

读取 JSON 文件(可选地使用点路径表示法返回属性)

function read_json($path, $prop = NULL, $default = NULL)

示例

$prop = read_json('file'[, 'package.details.name', 'untitled'\);

fix_json

将 JavaScript 对象转换为有效的 JSON

function fix_json($string, $fixNames = TRUE, $asArray = TRUE)

read_config

将环境文件解析为哈希

function read_config($path, $name = NULL)

dot_env

将 .env 文件读入环境变量

function dot_env($path)

write_file

写入文件(可选地对非标量数据进行 json_encoding)并返回文件名(如果成功)

function write_file($fn, $data, $append = FALSE)

write_json

使用点路径表示法更新现有 json 文件的设置(属性数组)

function write_json($path, array $props, $saveAs = NULL)

示例

$result = write_json('file', ['package.details.name' => 'test', 'version' => 2][, 'save-as']); //true or false

jwt_encode

使用 $key 对负载进行 JWT 编码

function jwt_encode($payload, $key = '')

示例

$token = jwt_encode(['user_id' => 1][, 'secret' | env(APP_KEY)]);

jwt_decode

使用 $key 解码 JWT 负载并验证它

function jwt_decode($jwt, $key = '')

示例

$result = jwt_decode('token'[, 'secret' | env(APP_KEY)]);

unix_path

将所有内容转换为正斜杠

function unix_path($path)

dos_path

将所有内容转换为反斜杠

function dos_path($path)

relative_path

将绝对路径转换为相对路径

function relative_path($docRoot, $path)

示例

$relPath = relative_path('d:/songs', 'd:/songs/coldplay/amsterdam.txt');

temp_file

创建具有给定扩展名和前缀的临时文件

function temp_file($ext = 'tmp', $prefix = 'tmp')

image_size

获取 [宽度,高度] 的图像

function image_size($path)

placeholder_image

返回随机占位符图像

function placeholder_image($width = 320, $height = 200, $type = 'any')

make_thumb

从任何图像创建缩略图

function make_thumb($src, $dest, $max_width = 100, $max_height = 100)

home_dir

获取当前用户的家目录

function home_dir()

directory

返回目录中的所有文件

function directory($path, $depth = -1, $regex = NULL, $exclude = [], $sort = FALSE, $includeDirs = FALSE)

示例

$files = directory('c:/tmp', depth [0 = no recursion, 1 = 1 level, -1 infinite], '/\.php$/' (optional regex for basename), [..dirs to exclude]);

deltree

@param SplFileInfo $file @param mixed $key @param RecursiveCallbackFilterIterator $iterator

@return bool True 如果需要递归或项目可接受

function deltree($dir)

mime_type

返回任何文件的 MIME 类型

function mime_type($fileName)

示例

$mime = mime_type('test.jpg');

basename_url

返回 URL 的最后一部分(不带查询字符串)

function basename_url($url)

网络相关函数

curl

使用 CURL 执行 GET/POST 请求,使用 $params

function curl($url, $method = 'get', $params = [], $headers = [], &$status = NULL)

示例

$response = url_get('http://www.google.com/search', 'get', ['q' => 'test'] | json (post body), ['header1', 'header2'], &$status);

upload

将数据保存到 Amazon S3

function upload($data, $fileName, $bucket, $mime = '', $acl = 'public-read')

upload_file

将文件上传到 Amazon S3

function upload_file($file, $bucket, $path = '', $mime = '', $acl = 'public-read')

s3_contents

列出 S3 存储桶的内容

function s3_contents($bucket, $path = '', $fileName = '/')

示例

$list = s3_contents('bucket', 'dir'); // returns all files in dir, $file_data = s3_contents('bucket', '', 'path_to_file'); // returns file's data instead

decode_image_data

@var \SimpleXMLElement $tag *

function decode_image_data($data, &$type = [])

gravatar

根据邮箱返回 Gravatar URL

function gravatar($email, $null_if_missing = FALSE)

is_disposable_email

检查电子邮件地址是否为一次性邮箱

function is_disposable_email($email, $mx_check = TRUE)

blank_image

返回空白图像的数据

function blank_image($type = 'gif')

示例

$data = blank_image('gif|png')

imgur

将图像上传到 imgur 并返回其在线 URL

必须定义以下环境变量:IMGUR_KEY

function imgur($path)

dom_path

创建一个 DOM 文档并返回其 xpath 选择器

对于 CSS 选择器:使用 BrowserKit 或 pQuery!更多信息请参阅:[链接](https://stackoverflow.com/a/260609/1031454)

function dom_path($html)

示例

$xpath = dom_path(curl('http://www.example.com')); // foreach($xpath->query('//h1') as $node) print $node->textContent;

download

下载文件

function download($url, $file = NULL, $headers = [])

示例

$file = download('http://www.bakalafoundation.org/wp/wp-content/uploads/2016/03/Google_logo_420_color_2x-1.png'[, 'c:/tmp/test.jpg']);

email

使用 Amazon SES 发送电子邮件

必须定义以下密钥:AWS_SECRET_ACCESS_KEY, AWS_ACCESS_KEY_ID

function email($to, $subject, $body, $attach = NULL)

domain

从 URL 获取域名,无论是否有子域名

function domain($url, $tld = TRUE)

fake_data

从 uinames.com 返回虚假用户数据

function fake_data()

示例

$user = fake_data();

today

其他函数

以 dd-mm-yyyy 格式返回今天的日期(UTC)

function today($format = 'dd-mm-yyyy', $time = NULL)

示例

$v = today('dd/mm/yy')

elapsed

显示自 $time 以来经过的秒数

function elapsed($time, $now = NULL)

mysql_date

将任何日期转换为 Mysql 格式

function mysql_date($date = NULL)

is_debug

检查是否启用了调试,即全局 $debug 变量是否设置或 DEBUG 环境存在

function is_debug()

debug

打印到 STDERR

function debug(...$args)

warning

以红色颜色打印到 STDERR

function warning(...$args)

app_dir

返回应用程序的基本目录

function app_dir($path = NULL, $check_exists = TRUE)

log_to_file

向日志文件写入一行

function log_to_file($file, ...$args)

log_error

在 ~/error.log 中记录错误

function log_error(...$args)

ip_address

获取本地 IP 地址

function ip_address()

env

返回环境变量的值

function env($name, $default = NULL)

os

返回操作系统名称(windows、mac 或 linux)

function os()

cmd

使用 system 运行命令

  • 如果任何参数以 @ 开头(或不是标量),则将其保存到 tmpfile,并使用文件路径代替
  • 如果第一个参数是 "false",则命令为 dry-run

cmd('curl -F "data=@%s" -F "userid=%d" [链接](http://example.com)', '@{"json":"data"}', 3); 将自动将第一个参数保存到文件中,并插入其路径

function cmd(...$args)

bg

在后台运行进程

function bg(...$args)

cmd_capture

使用反引号捕获命令的输出并修剪输出

function cmd_capture(...$args)

cmd_parallel

使用 xargs 并行运行命令

function cmd_parallel(array $commands, int $max_parallel = 3)

示例

$o = cmd_parallel(['youtube-dl 1', 'youtube-dl 2', 'php sleep.php'], 3);

cache_memory

将值(读取/写入)缓存到内存中

function cache_memory($key, $value = NULL)

示例

$r = cache_memory('key', [1, 2]);

cache_local

将值(读取/写入)缓存到文件缓存中

function cache_local($key, $value = NULL, $expires = 86400, $refresh = FALSE)

示例

$r = cache_local('key', [1, 2], -86400, true); //fresh result - cache for 86400

confirm

等待命令行确认

function confirm($msg = 'Are you sure?', $default = 'y', $accept = '/^y/i')

dump

将变量输出到屏幕或浏览器(带有适当的格式化)

function dump(...$args)

encrypt_str

加密字符串

function encrypt_str($string, $password = '')

decrypt_str

使用 encrypt 加密编码的字符串进行解密

function decrypt_str($string, $password = '')

is_cli

检查 PHP 是否在 CLI 模式下运行

function is_cli()

get_argv

从命令行按名称(或别名)获取参数

@return mixed

function get_argv($name = NULL, $default = NULL)

示例

$val = get_argv('name', null);

show_errors

显示或隐藏所有错误

function show_errors($show = TRUE)