repat / php-helper
为使用 PHP 7.2+ 开发应用程序提供的一些辅助函数
Requires
- php: >=7.2
- ext-curl: *
- nesbot/carbon: ^1.26.3 || ^2.0
- repat/date-constants: *
- repat/http-constants: *
- stevegrunwell/time-constants: *
Suggests
- jeremykendall/php-domain-parser: Required in ^6.0 to parse domains with domain()
- league/commonmark: Required to use markdown2html()
README
php-helper 是一个包含我开发 PHP 应用程序时发现有用的辅助函数的包。所有函数都通过 functions_exists()
进行包装,以防止冲突。
⚠️ 其中一些函数曾经位于
repat/laravel-helper
中,现在这个包是这个包的依赖项。
还可以查看以下内容
- https://laravel.net.cn/docs/8.x/helpers
- http://calebporzio.com/11-awesome-laravel-helper-functions
- https://packagist.org.cn/packages/illuminated/helper-functions
- https://packagist.org.cn/packages/laravel/helper-functions
这里应该包含哪些内容?请提交一个拉取请求或发送电子邮件!
安装
$ composer require repat/php-helper
文档
数组
array_equal($arr1, $arr2)
确定两个数组是否具有相同的项,不受顺序的影响。
$arr1 = [1, 2, 3]; $arr2 = [3, 2, 1]; array_equal($arr1, $arr2); // returns: true $arr3 = [4, 5, 6]; array_equal($arr1, $arr3); // returns: false
array_key2value($array)
返回一个数组,其中键等于值。这是 array_combine($array, $array);
的语法糖。
$array = [1, 3, 5]; print_r(array_key2value($array)); // returns: Array( [1] => 1, [3] => 3, [5] => 5 )
array_delete_value($array, $value)
从 $array
中删除所有具有值 $value
的元素。本质上是对 array_diff()
的语法糖。
$array = ['foo', 'bar']; print_r(array_delete_value($array, 'foo')); // returns Array( [1] => "bar" )
contains_duplicates($array)
检查给定的数组中是否有重复项。
contains_duplicates([1, 1]); // returns: true contains_duplicates([1, 2]); // returns: false
array_change_keys($array, $keys)
递归地更改关联数组的键。第二个参数是一个数组,其中包含旧键($array
的键)作为键,新键作为值。
$array = [ 'bar' => 'foo', 'sub' => [ 'some' => 'thing', ], ]; $keys = [ 'bar' => 'biz', // change all 'bar' keys to 'biz' keys 'some' => 'any', ]; array_change_keys($array, $keys); // returns:[ // 'biz' => 'foo', // 'sub' => [ // 'any' => 'thing', // ], // ];
array_key_replace($array, $oldKey, $newKey)
类似于 array_change_keys()
,但它仅适用于一维数组。
array_key_replace(['bar' => 'foo'], 'bar', 'bizz'); // returns : ['bizz' => 'foo']
array_avg($array)
计算值的平均值(总和/数量)。如果数组为空,则返回 null
。
array_avg([1, 2, 3]); // returns : 2 array_avg([]); // returns : null
日期
days_in_month($month = null, $year = null)
返回给定月份或年份的天数。默认为当前月份和年份。
days_in_month(); // returns: 31 (for e.g. May) days_in_month($april = 4); // returns: 30 days_in_month($feb = 2, $year = 2020); // returns: 29 (2020 is a leap year)
days_this_month()
返回当前月份的天数。
days_this_month(); // returns: 31 (for e.g. May)
days_next_month()
返回下个月的天数。
days_next_month(); // returns: 30 (for e.g. May because June has 30)
days_this_year()
返回当前年的天数。
days_this_year(); // returns: 365 (because it's not a leap year)
days_left_in_month()
返回当前月份剩余的天数。
days_left_in_month(); // returns: 29 (on 1st April)
days_left_in_year()
返回当前年份剩余的天数。
days_left_in_year(); // returns: 274 (on 1st April 2019)
timezone_list()
返回所有时区的列表。
timezone_list(); // returns: // [ // "Pacific/Pago_Pago" => "(UTC-11:00) Pacific/Pago_Pago", // "Pacific/Niue" => "(UTC-11:00) Pacific/Niue", // "Pacific/Midway" => "(UTC-11:00) Pacific/Midway", // ... // "Pacific/Chatham" => "(UTC+13:45) Pacific/Chatham", // "Pacific/Kiritimati" => "(UTC+14:00) Pacific/Kiritimati", // "Pacific/Apia" => "(UTC+14:00) Pacific/Apia", // ];
tomorrow()
类似于 today()
或 now()
,此函数返回一个表示明天的 Carbon 实例。
tomorrow(); // returns: Carbon\Carbon @1554156000 {#5618 // date: 2019-04-20 00:00:00.0 Europe/Amsterdam (+02:00), // }
yesterday()
类似于 today()
或 now()
,此函数返回一个表示昨天的 Carbon 实例。
yesterday(); // returns: Carbon\Carbon @1554156000 {#5618 // date: 2019-04-19 00:00:00.0 Europe/Amsterdam (+02:00), // }
seconds2minutes($seconds)
返回具有 60+ 分钟的 i:s
字符串,而不是显示小时。
seconds2minutes(42); // returns: 00:42 seconds2minutes(90); // returns: 01:30 seconds2minutes(4223); // returns: 70:23
diff_in_days($start, $end)
使用 Carbons 的 diffInDays()
和 parse()
方法返回天数差异。
diff_in_days('2018-04-19', '2018-04-21'); // returns: 2 diff_in_days(today(), yesterday()); // returns: 1
对象
object2array($object)
对象的数组表示形式,例如 Eloquent 模型。
use App\Models\User; object2array(User::first()); // returns: [ // "casts" => [ // "someday_at" => "datetime", // // ... // ], // "incrementing" => true, // "exists" => true, // "wasRecentlyCreated" => false, // "timestamps" => true, // ]
filepath2fqcn($filepath, $prefix = '')
将文件路径转换为完全限定类名。
filepath2fqcn('/Users/john/code/app/Models/User.php', '/Users/john/code/'); // returns: App\Models\User filepath2fqcn('/Users/john/code/app/Models/User.php', '/Users/john/code'); // returns: App\Models\User filepath2fqcn('app/Models/User.php'); // returns: App\Models\User filepath2fqcn('/Users/john/code/app/Models/User.php'); // returns: \Users\john\code\app\Models\User
Misc
toggle($switch)
如果给定 true
,则返回 false
,反之亦然。
toggle(false); // returns: true toggle(true); // returns: false
generate_password($size = 15)
返回一个随机密码。这是 str_random()
的语法糖。
generate_password(); // returns: IZeJx3MeUdDhzE2
auto_cast($value)
返回具有正确类型的值,例如您可以使用 ===
进行类型安全比较。
gettype(auto_cast('42')); // returns: integer gettype(auto_cast('42.0')); // returns: double gettype(auto_cast('true')); // returns: boolean
human_filesize($size)
返回给定字节的可读形式。可达到 Yottabyte。
human_filesize(4223); // returns: 4.12kB
permutations($array)
返回给定数组值的所有可能排列的生成器。
基于eddiewoulds 端口端口,将python 代码移植。
$gen = permutations(['foo', 'bar', 'biz']); iterator_to_array($gen) // returns: [ // [ // "foo", // "bar", // "biz", // ], // [ // "foo", // "biz", // "bar", // ], // [ // "bar", // "foo", // "biz", // ], // [ // "bar", // "biz", // "foo", // ], // [ // "biz", // "foo", // "bar", // ], // [ // "biz", // "bar", // "foo", // ], // ]
zenith($type)
封装用于Zenith的魔法数字。类型可以是:
天文学
: 108.0航海学
: 102.0民用
: 96.0- 默认值:90+50/60 (~90.83)
zenith('civil'); // returns: 96.0
operating_system()
返回以下常量之一(也请参阅常量部分)
macos
windows
linux
bsd
operating_system(); // returns: linux LINUX // returns: linux
wikipedia($lemma, $lang = 'en', $return = '')
链接到特定语言的维基百科
wikipedia('Towel Day'); // returns: https://en.wikipedia.org/wiki/Towel_Day wikipedia('Paris', 'fr', '#') // returns: https://fr.wikipedia.org/wiki/Paris wikipedia('Pariz', 'fr', '#') // returns: #
function_location($functionName)
使用Reflection返回函数定义的位置,如果函数不存在则返回 null
。注意,PHP 的内部函数返回一个空字符串。
function_location('wikipedia') // returns: /folder/on/drive/php-helper/src/misc_helper.php:198 function_location('function_does_not_exist') // returns: null function_location('array_map') // returns: '' (empty string)
网络
scrub_url($url)
从 URL 中移除协议、www 和尾部斜杠。然后您可以例如测试 HTTP 与 HTTPS 连接。
scrub_url('https://www.repat.de/'); // returns: 'repat.de' scrub_url('https://blog.fefe.de/?ts=a262bcdf'); // returns: 'blog.fefe.de/?ts=a262bcdf'
http_status_code($url, $follow = true, $userAgent = null)
通过发送一个空的请求返回状态码。默认情况下,它遵循重定向,因此它将只返回最后一个状态码,而不是例如 301 重定向。通过将第二个参数设置为 false
来禁用重定向。某些网站需要用户代理并返回另一个状态码。可以将字符串传递给 $userAgent
。需要 ext-curl
。
http_status_code('httpstat.us/500'); // returns: 500 http_status_code('http://repat.de'); // with 301 redirect to https://repat.de // returns: 200 http_status_code('http://repat.de', false); // returns: 301
parse_signed_request($request, $clientSecret, $algo)
解析 HMAC 签名请求。从 Data Deletion Request Callback - Facebook for Developers 复制。默认 $algo
为 sha256
。
$requestString = null; // TODO parse_signed_request($requestString, env('FACEBOOK_CLIENT_SECRET'));
domain_slug($domain)
验证域名并创建一个缩略名。对于子域名不适用,请改用 sluggify_domain()
。在解析错误时返回 null
。
domain_slug('blog.fefe.de') //returns: blogfefede domain_slug('blogfefe.de') //returns: blogfefede
gethostbyname6($domain)
使用 DNS AAAA 记录通过给定的域名返回一个 IPv6 地址。如果没有找到,则返回输入的域名,类似于 gethostbyname()
对 IPv4 所做的。
gethostbyname6('ipv4onlydomain.tld'); // returns: ipv4onlydomain.tld gethostbyname6('example.com') // returns: 2606:2800:220:1:248:1893:25c8:1946
is_public_ip($ip)
返回给定的 IP 是否是公共 IPv4 或 IPv6 地址(与专用或保留地址相对)
is_public_ip('127.0.0.1'); // localhost // returns: false is_public_ip('::1/128'); // localhost // returns: false is_public_ip('192.168.1.42') // private network // returns: false $ipv4 = gethostbyname('example.com'); is_public_ip($ipv4); // returns: true $ipv6 = gethostbyname6('example.com'); is_public_ip($ipv6); // returns true;
final_redirect_target($url)
跟随所有 301/302 重定向并返回链尾的 URL,或返回 null
。
final_redirect_target('http://google.com'); // returns http://www.google.com
字符串
str_icontains($haystack, $needle)
类似于 Str::contains() 但不区分大小写。
str_icontains('FOOBAR', 'foo'); // returns: true str_icontains('foobar', 'foo'); // returns: true str_icontains('foobar', 'FOO'); // returns: true str_icontains('foobar', 'test'); // returns: false
to_ascii($string)
删除所有非 ASCII 字符并返回剩余的部分。
to_ascii('René'); // returns: Ren
hyphen2_($string)
将所有连字符 ("-") 字符替换为下划线 ("_")。
hyphen2_('foo-bar'); // returns: foo_bar
_2hypen($string)
将所有下划线 ("_") 字符替换为连字符 ("-")。
_2hypen('foo_bar'); // returns: foo-bar
str_replace_once($search, $replace, $string)
具有与 str_replace()
相同的签名,但如名称所示,只替换 $search
的第一个出现。
str_replace_once('foo', 'bar', 'foofoo'); // returns: 'barfoo'
title_case_wo_underscore($string)
标题大小写,但没有下划线。
title_case_wo_underscore('foo_bar'); // returns: Foo Bar // vs. // title_case('foo_bar') // returns: Foo_Bar
lorem_ipsum()
返回 Lorem Ipsum 占位文本的示例。
lorem_ipsum(); // returns: // Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
sluggify_domain($domain)
通过将点号替换为下划线返回域名的缩略版本。与 str_slug()
不同,它不适用于子域名,因为它会完全删除点号。
sluggify_domain('blog.fefe.de'); // returns: blog_fefe_de str_slug('blog.fefe.de'); // returns: blogfefede sluggify_domain('blogfefe.de'); // returns: blogfefe_de str_slug('blogfefe.de'); // returns: blogfefede // same as subdomain on fefe.de
str_remove($string, $remove)
删除给定的字符串、数字或字符串数组。是 str_replace($remove, '', $string)
的语法糖。
str_remove('foobar', 'bar'); // returns: foo str_remove('foobar42', ['foo', 'bar']); // returns: 42 str_remove('foobar42', 42); // returns: foobar
str_bytes($string)
返回字符串中的字节数。
str_bytes('foobar'); // returns: 6 str_bytes('fooßar'); // returns: 8
regex_list($array)
使用正则表达式创建一个以 OR 分隔的字符串。
regex_list(['foo', 'bar', '42']) // returns: \bfoo|\bbar|\b42
base64_url_decode($url)
解码一个 base64 编码的 URL。内容来源于 数据删除请求回调 - Facebook 开发者
base64_url_decode('aHR0cHM6Ly9yZXBhdC5kZQ=='); // returns: https://repat.de
str_right($string, $until)
是 str_after
的语法糖。
str_right('https://vimeo.com/165053513', '/'); // returns: 165053513
str_left($string, $before)
是 str_before
的语法糖。
str_left('https://vimeo.com/165053513', '165053513'); // returns: https://vimeo.com/
normalize_nl($string)
将所有换行字符(\r
、\n
、\r\n
)标准化为 UNIX 换行符 \n
。
normalize_nl('foobar\r\n'); // Windows // returns: foobar\n normalize_nl('foobar\r'); // MacOS // returns: foobar\n normalize_nl('foobar\n'); // *nix // returns: foobar\n
str_count_upper($string)
计算字符串中的大写字母数量。另见 str_count_lower()
。
str_count_upper('FoObAr'); // returns: 3 str_count_upper('foobar'); // returns: 0 str_count_upper('FOOBAR'); // returns: 6
str_count_lower($string)
计算字符串中的小写字母数量。另见 str_count_upper()
。
str_count_lower('FoObAr'); // returns: 3 str_count_lower('foobar'); // returns: 6 str_count_lower('FOOBAR'); // returns: 0
str_insert_bindings($sql, $bindings)
在 SQL 字符串中插入 ?
字符的绑定。另见 insert_bindings()
of repat/laravel-helper
。
str_insert_bindings('SELECT * FROM `table` WHERE id = ?', [42]); // returns: SELECT * FROM `table` WHERE id = '42'
contains_uppercase($string)
如果给定的字符串包含至少一个 ASCII 大写字母。
contains_uppercase('Foobar'); // returns: true contains_uppercase('foobar'); // returns: false contains_uppercase('FOOBAR'); // returns: true
contains_lowercase($string)
如果给定的字符串包含至少一个 ASCII 小写字母。
contains_lowercase('Foobar'); // returns: true contains_lowercase('foobar'); // returns: true contains_lowercase('FOOBAR'); // returns: false
contains_numbers($string)
如果给定的字符串(或数字)包含至少一个数字。
contains_numbers('Foobar'); // returns: false contains_numbers('Foobar42'); // returns: true contains_numbers('42'); // returns: true contains_numbers(42); // uses strval() // returns: true
country_name($iso, $locale)
将 ISO Code 3166-1 alpha-2 的 $iso
代码转换为完整的国家名称。基本上是 locale_get_display_region()
的语法糖。可选地接受 $locale
以在给定语言中打印国家名称。 XK
将给出 科索沃。
country_name('nz'); // returns: New Zealand country_name('de'); // returns: Germany (Germany in English) country_name('de', 'de'); // returns: Deutschland (Germany in German)
Wordpress
这些函数是从开源内容管理系统 Open Source Content Management System Wordpress 中提取的,该系统在 GPL 2(或更高版本)下发布。
mbstring_binary_safe_encoding()
reset_mbstring_encoding()
seems_utf8()
remove_accents($string)
移除特殊字符,并用它们的 ASCII 对应字符替换。
remove_accents('á'); // returns: a remove_accents('René') // returns: Rene
可选包
此建议的这些可选包是这些函数正常工作所必需的。
markdown2html($markdown)
使用 league/commonmark 将 Markdown 转换为 HTML。
$ composer require league/commonmark
markdown2html('# Header'); // returns: <h1>Header</h1>\n
domain($url, $publicSuffixList)
使用 jeremykendall/php-domain-parser 从 URL 返回域名,删除协议、子域(包括 www)和路径。为此,该包需要一个公共后缀列表,该列表可在 publicsuffix.org 找到。
$ composer require jeremykendall/php-domain-parser
// Don't use this code, it's just to illustrate where the file could be $publicSuffixList = file_get_contents('https://publicsuffix.org/list/public_suffix_list.dat'); $path = '/tmp/public_suffix_list.dat'; file_put_contents($path, $publicSuffixList); // ... domain('https://repat.de/about?foo=bar', $path); // returns: repat.de
HTML
linkify($string, $protocols = ['http', 'https', 'mail'], $attributes)
将所有给定协议的 URL 转换为链接。可选地,可以传递 a 标签 的属性。
linkify('https://google.com is a search engine'); // returns: <a href="https://google.com">google.com</a> is a search engine linkify('https://google.com is a search engine', ['https'], ['target' => '_blank']); // returns: <a target="_blank" href="https://google.com">google.com</a> is a search engine
embedded_video_url($url)
返回给定 YouTube 或 Vimeo URL 的嵌入版本。
embedded_video_url('https://www.youtube.com/watch?v=dQw4w9WgXcQ'); // returns: https://www.youtube.com/embed/dQw4w9WgXcQ embedded_video_url('https://vimeo.com/50491748'); // returns: https://player.vimeo.com/video/50491748
ul_li_unpack($array, $separator)
将关联数组解包到一个无序列表。默认分隔符为:
。
ul_li_unpack(['foo' => 'bar']); // returns: <ul><li>foo: bar</li></ul> ul_li_unpack(['foo' => 'bar'], '=>'); // returns: <ul><li>foo=> bar</li></ul>
contrast_color($bgColor)
使用亮度对比算法确定对于给定的十六进制背景颜色,白色或黑色是否是最好的对比颜色。
来源: tomloprod on stackoverflow
contrast_color('b9b6b6'); // returns: #000000 contrast_color('#496379'); // returns: #ffffff
标志
emoji_flag($iso)
返回ISO-3166 alpha-2代码的emoji国旗,例如nz
代表新西兰或py
代表巴拉圭。大小写不区分。对于不存在的国家代码(或者更确切地说,Unicode没有对应的国旗),将返回一个挥动的黑色国旗或null
。 XK
将返回科索沃的国旗。
emoji_flag('nz'); // returns: 🇳🇿 emoji_flag('PY'); // returns: 🇵🇾 emoji_flag(null); // returns: 🏴
常量
PARETO_HIGH
: 80PARETO_LOW
: 20MARIADB_DEFAULT_STRLEN
: 191ONE_HUNDRED_PERCENT
: 100KILO
: 1000KIBI
: 1024NBSP
:\xc2\xa0
CR
:\r
LF
:\n
CRLF
:\r\n
HTTP_1_0_VERBS
: [get, head, post]HTTP_1_1_VERBS
: [get, head, post, connect, delete, options, put, trace]HTTP_VERBS
: [get, head, post, connect, delete, options, put, trace, patch]REGEX_WORD_BOUNDARY
: \bREGEX_FIRST_RESULT_KEY
: 1REGEX_UPPERCASE_ASCII
: (A-Z)REGEX_LOWERCASE_ASCII
: (a-z)REGEX_NUMBERS
: (0-9)REGEX_NEWLINES
: \n|\r\n?MACOS
: macosWINDOWS
: windowsLINUX
: linuxBSD
: bsdEXIT_SUCCESS
: 0EXIT_FAILURE
: 1HEX_RED
: #ff0000HEX_GREEN
: #00ff00HEX_BLUE
: #0000ffHEX_WHITE
: #ffffffHEX_BLACK
: #000000WEAK_CIPHERS
: [ TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA]INET_ADDRSTRLEN
: 16INET6_ADDRSTRLEN
: 46
贡献者
许可
- MIT, see LICENSE
版本
- 版本 0.1.22
联系方式
repat
- 主页: https://repat.de
- 电子邮件: repat@repat.de
- Twitter: @repat123