php 在 x 个字符后拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5200940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
split string after x characters
提问by TDSii
How to split $string after 5 characters into an array
如何将 5 个字符后的 $string 拆分为数组
example:
例子:
$string="123456789";
expected output
预期产出
$output[0] contain "12345";
$output[1] contain "6789";
采纳答案by TDSii
With the help of BoltClocks' answer I have created the following function to solve the problem:
在 BoltClocks 的回答的帮助下,我创建了以下函数来解决问题:
function split_on($string, $num) {
$length = strlen($string);
$output[0] = substr($string, 0, $num);
$output[1] = substr($string, $num, $length );
return $output;
}
回答by BoltClock
If you need to split a string after every5 characters, try str_split()
:
如果您需要在每5 个字符后拆分一个字符串,请尝试str_split()
:
$output = str_split($string, 5);
If you only need to extract the first 5 characters and put the rest of the string in the second part of your array, you can use substr()
as NullUserException suggests (code from his now-deleted answer):
如果您只需要提取前 5 个字符并将字符串的其余部分放在数组的第二部分,您可以substr()
按照 NullUserException 建议使用(来自他现已删除的答案的代码):
$output[0] = substr($string, 0, 5);
$output[1] = substr($string, 5);