使用 PHP 按长度将字符串拆分为 2 段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6822683/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:23:13  来源:igfitidea点击:

Split string into 2 pieces by length using PHP

phpstringsplit

提问by Paul

I have a very long string that I want to split into 2 pieces.

我有一个很长的字符串,我想分成两部分。

I ws hoping somebody could help me split the string into 2 separate strings.

我希望有人能帮我把字符串分成 2 个单独的字符串。

I need the first string to be 400 characters long and then the rest in the second string.

我需要第一个字符串的长度为 400 个字符,然后第二个字符串中的其余字符串。

回答by Paul

$first400 = substr($str, 0, 400);
$theRest = substr($str, 400);

You can rename your variables to whatever suits you. Those names are just for explanation. Also if you try this on a string less than 400 characters $theRest will be FALSE

您可以将变量重命名为适合您的任何名称。这些名字只是为了解释。此外,如果您在少于 400 个字符的字符串上尝试此操作,则 $theRest 将是FALSE

回答by hakre

There is a function called str_splitPHP Manualwhich might, well, just split strings:

有一个名为str_splitPHP Manual的函数,它可能只是拆分字符串:

$parts = str_split($string, $split_length = 400);

$partsis an arraywith each part of it being 400 (single-byte) characters at max. As per this question, you can as well assign the first and second part to individual variables (expecting the string being longer than 400 chars):

$parts它的array每个部分最多为 400 个(单字节)字符。根据这个问题,您也可以将第一部分和第二部分分配给各个变量(期望字符串长于 400 个字符):

list($str_1, $str_2) = str_split(...);