Split string into 2 pieces by length using PHP

前端 未结 3 1802
别跟我提以往
别跟我提以往 2021-01-17 08:00

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 s

相关标签:
3条回答
  • 2021-01-17 08:06

    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(...);
    
    0 讨论(0)
  • 2021-01-17 08:19
    $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

    0 讨论(0)
  • 2021-01-17 08:20

    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));
    
    ?>
    
    0 讨论(0)
提交回复
热议问题