Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string into two equal length parts using PHP [duplicate]

I need to split a string into two equal length parts.String can contain blank spaces, commas or anything. I have referred and tries the code sample of explode statement from the link http://www.testingbrain.com/php-tutorial/php-explode-split-a-string-by-string-into-array.html but there it not showing any sample for splitting by equal length.

One more thing, while splitting words shouldn't broken.

like image 869
syam Avatar asked Sep 26 '22 11:09

syam


1 Answers

This will split without breaking the word, at the most possible half of the text, but it may split at any other characters (,,.,@ etc)

$data = "Split a string by length without breaking word"; //string

if (strlen($data) % 2 == 0) //if lenhth is odd number
    $length = strlen($data) / 2;
else
    $length = (strlen($data) + 1) / 2; //adjust length

for ($i = $length, $j = $length; $i > 0; $i--, $j++) //check towards forward and backward for non-alphabet
{
    if (!ctype_alpha($data[$i - 1])) //forward
    {
        $point = $i; //break point
        break;
    } else if (!ctype_alpha($data[$j - 1])) //backward
    {
        $point = $j; //break point
        break;
    }
}
$string1 = substr($data, 0, $point);
$string2 = substr($data, $point);
like image 163
Subin Thomas Avatar answered Sep 29 '22 08:09

Subin Thomas