使用 PHP 将字符串按长度分成 2 部分

发布于 2024-11-26 10:20:00 字数 107 浏览 1 评论 0 原文

我有一根很长的绳子,我想把它分成两段。

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

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

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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

挽清梦 2024-12-03 10:20:00
$first400 = substr($str, 0, 400);
$theRest = substr($str, 400);

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

$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

故事未完 2024-12-03 10:20:00

有一个名为 str_split 的函数PHP 手册 可能只是分割字符串:

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

$parts 是一个 数组,每个部分最多 400 个(单字节)字符。根据这个问题,您也可以将第一部分和第二部分分配给各个变量(预计字符串长度超过 400 个字符):

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

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

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

$parts is an array with 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):

list($str_1, $str_2) = str_split(...);
余罪 2024-12-03 10:20:00

如果您想将字符串分成 n 个相等的部分,这是另一种方法

<?php

$string = "This-is-a-long-string-that-has-some-random-text-with-hyphens!";
$string_length = strlen($string);

switch ($string_length) {

  case ($string_length > 0 && $string_length < 21):
    $parts = ceil($string_length / 2); // Break string into 2 parts
    $str_chunks = chunk_split($string, $parts);
    break;

  default:
    $parts = ceil($string_length / 3); // Break string into 3 parts
    $str_chunks = chunk_split($string, $parts);
    break;

}

$string_array = array_filter(explode(PHP_EOL, $str_chunks));

?>

This is another approach if you want to break a string into n number of equal parts

<?php

$string = "This-is-a-long-string-that-has-some-random-text-with-hyphens!";
$string_length = strlen($string);

switch ($string_length) {

  case ($string_length > 0 && $string_length < 21):
    $parts = ceil($string_length / 2); // Break string into 2 parts
    $str_chunks = chunk_split($string, $parts);
    break;

  default:
    $parts = ceil($string_length / 3); // Break string into 3 parts
    $str_chunks = chunk_split($string, $parts);
    break;

}

$string_array = array_filter(explode(PHP_EOL, $str_chunks));

?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文