28

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.

Paul
  • 139,544
  • 27
  • 275
  • 264
  • 2
    There still is a section in the PHP Manual called **[String Functions](http://www.php.net/manual/en/ref.strings.php)**. ***And:*** Going through your previous questions I cannot but notice that there is lots of questions that are easily answered by searching the PHP Manual or Google or Stack Overflow. You are encouraged to do some research before asking new questions here. See http://stackoverflow.com/questions/ask-advice – hakre Jul 25 '11 at 21:52
  • 2
    possible duplicate of [Split string into equal parts using PHP](http://stackoverflow.com/questions/1794006/split-string-into-equal-parts-using-php) – hakre Jul 25 '11 at 22:06
  • 1
    It's not actually a duplicate of that, I don't think. This is looking to pull out a "teaser" of N characters to one string, then the rest of the original to a second string - only 2 total. The linked question is asking to split the string into as many parts as needed. – squarecandy Dec 18 '13 at 20:24
  • 1
    wow, seriously hakre? an RTFM response? – Scott Aug 23 '16 at 21:19

3 Answers3

70
$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

Paul
  • 139,544
  • 27
  • 275
  • 264
23

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(...);
hakre
  • 193,403
  • 52
  • 435
  • 836
0

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));

?>
AhmadKarim
  • 899
  • 1
  • 7
  • 16