为字符串的指定位置添加指定字符(有示例),例如电话号码第 3 位 与 第 7 位 之后添加 - 、流水号的第 8,12,16,20 位之后添加 - 或指定字符串。
为字符串的指定位置添加指定字符
function offset(&$str, array $offset, $delimiter = '-') {
foreach ($offset as $i => $v) {
$str = mb_substr_replace($str, $delimiter, $i + $v, 0);
}
return $str;
}
这里是社区中大神 @Hanccc 写的一个感觉更好的代码及 demo
mb_substr_replace() 为自定义方法。mb_substr_replace() Gist 地址 :
https://gist.githubusercontent.com/stemar/...
mb_substr_replace() :
<?php
function mb_substr_replace($string, $replacement, $start, $length=NULL) {
if (is_array($string)) {
$num = count($string);
// $replacement
$replacement = is_array($replacement) ? array_slice($replacement, 0, $num) : array_pad(array($replacement), $num, $replacement);
// $start
if (is_array($start)) {
$start = array_slice($start, 0, $num);
foreach ($start as $key => $value)
$start[$key] = is_int($value) ? $value : 0;
}
else {
$start = array_pad(array($start), $num, $start);
}
// $length
if (!isset($length)) {
$length = array_fill(0, $num, 0);
}
elseif (is_array($length)) {
$length = array_slice($length, 0, $num);
foreach ($length as $key => $value)
$length[$key] = isset($value) ? (is_int($value) ? $value : $num) : 0;
}
else {
$length = array_pad(array($length), $num, $length);
}
// Recursive call
return array_map(__FUNCTION__, $string, $replacement, $start, $length);
}
preg_match_all('/./us', (string)$string, $smatches);
preg_match_all('/./us', (string)$replacement, $rmatches);
if ($length === NULL) $length = mb_strlen($string);
array_splice($smatches[0], $start, $length, $rmatches[0]);
return join($smatches[0]);
}
调用
-
流水号
function ticket($offset = [8,12,16,20]) { $str = (\Ramsey\Uuid\Uuid::uuid1())->getHex(); offset($str, $offset); return strtoupper($str); } $ticket = ticket(); // 4D879CB1-7101-DC10-E033-AB4161876CCE
-
电话号码。
$phone = 13112345678 offset($phone, [3, 7]) // 131-1234-5678
注意:所指定位置是原字符串的位置之后。
本作品采用《CC 协议》,转载必须注明作者和本文链接
高认可度评论:
有趣,但觉得楼主的代码太多,自己闲的蛋疼自己写了一遍,可以参考一下
有趣,但觉得楼主的代码太多,自己闲的蛋疼自己写了一遍,可以参考一下
@Hanccc 这个工具是神马!:joy:
@Hanccc 代码简洁,功能实现,给你个大大的赞:+1:
@蜗牛 http://sandbox.onlinephpfunctions.com/ 一般写 demo 代码我都不会打开编辑器或者 IDE,开这个就够了
@Hanccc 蟹蟹分享:kissing_heart:
添加一个支持中文的,代码如下:
附加一个代码量更少的,如下: