php - 如何使用 PHP 将“字符串”操作为给定格式
问题描述
我有 20 个数字|长度的字符串,例如:22223333333334444333
. 如何使用给定的格式进行操作,例如:00-00-000-000-000-0000-000
在 PHP 中?
预期结果:22-22-333-333-333-4444-333
解决方案
您可以使用一些正则表达式通过几个步骤完成它。
<?php
// Test string
$string = "22223333333334444333";
// Pattern: 22-22-333-333-333-4444-333
$pattern = "/([0-9]{2})([0-9]{2})([0-9]{3})([0-9]{3})([0-9]{3})([0-9]{4})([0-9]{3})/";
// Get all the matching elements in the pattern
preg_match($pattern, $string, $matches);
// Remove the first element from the results (it's the entire string, we don't want that)
array_shift($matches);
// Join all the others matches with "-"
$formatted = implode('-', $matches);
// And there you have your formatted string
var_dump($string, $formatted);
// Output
// '22223333333334444333' (length=20)
// '22-22-333-333-333-4444-333' (length=26)
推荐阅读
- docker - Rancher 机器重新启动时未显示集群
- go - 我的游戏中的圆形碰撞比图像略大
- pyspark - Jupyter Notebook 在启动时显示 No pyspark kernel
- python-3.x - 使用自然语言处理从段落中提取特定类型的单词
- apache-kafka - 无法建立到节点 -1 的连接。经纪人可能不可用。(org.apache.kafka.clients.NetworkClient)
- python - 如何在文件之间共享静态类变量?
- python - 当新用户在 JuPyter 集线器上注册/登录时,如何在启动文件夹中自动写入文件?
- amazon-web-services - 无法使用 virtual-kubelet 在 AWS Fargate 上创建 nginx 任务定义的部署
- windows - 将使用 electron-builder 创建的 appx 安装到我已安装的应用程序中后,将默认电子图标设置为
- hive - HIVE中的两个表比较