首页 > 解决方案 > 如何使用 PHP 将“字符串”操作为给定格式

问题描述

我有 20 个数字|长度的字符串,例如:22223333333334444333. 如何使用给定的格式进行操作,例如:00-00-000-000-000-0000-000在 PHP 中?

预期结果:22-22-333-333-333-4444-333

标签: php

解决方案


您可以使用一些正则表达式通过几个步骤完成它。

<?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)

推荐阅读