Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into 2 pieces by length using PHP

Tags:

string

php

split

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.


2 Answers

$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

like image 120
Paul Avatar answered Sep 07 '25 17:09

Paul


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(...);
like image 39
hakre Avatar answered Sep 07 '25 17:09

hakre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!