简体   繁体   English

划界密钥的最有效方法

[英]Most efficient way to delimit key

Say I have a string of 16 numeric characters (ie 0123456789012345) what is the most efficient way to delimit it into sets like : 0123-4567-8901-2345, in PHP? 假设我有一个由16个数字字符组成的字符串(即0123456789012345),在PHP中将其分隔为0123-4567-8901-2345之类的集合的最有效方法是什么?

Note: I am rewriting an existing system that is painfully slow. 注意:我正在重写速度非常慢的现有系统。

Use str_split() : 使用str_split()

$string = '0123456789012345';
$sets = str_split($string, 4);
print_r($sets);

The output: 输出:

Array
(
    [0] => 0123
    [1] => 4567
    [2] => 8901
    [3] => 2345
)

Then of course to insert hyphens between the sets you just implode() them together: 然后当然要在集合之间插入连字符,只需将它们一起爆破()

echo implode('-', $sets); // echoes '0123-4567-8901-2345'

If you are looking for a more flexible approach (for eg phone numbers), try regular expressions: 如果您正在寻找一种更灵活的方法(例如电话号码),请尝试使用正则表达式:

preg_replace('/^(\d{4})(\d{4})(\d{4})(\d{4})$/', '\1-\2-\3-\4', '0123456789012345');

If you can't see, the first argument accepts four groups of four digits each. 如果看不到,第一个参数将接受四组,每组四个数字。 The second argument formats them, and the third argument is your input. 第二个参数格式化它们,第三个参数是您的输入。

This is a bit more general: 这有点笼统:

<?php

// arr[string] = strChunk(string, length [, length [...]] );
function strChunk() {
    $n = func_num_args();
    $str = func_get_arg(0);
    $ret = array();

    if ($n >= 2) {
        for($i=1, $offs=0; $i<$n; ++$i) {
            $chars = abs( func_get_arg($i) );
            $ret[] = substr($str, $offs, $chars);
            $offs += $chars;
        }
    }

    return $ret;
}

echo join('-', strChunk('0123456789012345', 4, 4, 4, 4) );

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM