5

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.

syam
  • 106
  • 2
  • 9

3 Answers3

4

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);
Ryan Vincent
  • 4,483
  • 7
  • 22
  • 31
Subin Thomas
  • 1,408
  • 10
  • 19
1

here you go.

$str="Test string";
$middle=strlen($str)/2;
$first=substr($str,0,$middle);
$last=substr($str,$middle);
Reeno
  • 5,720
  • 11
  • 37
  • 50
0

I think this is are good start:

$string = "My name is StackOcerflow and I like programming, one more comma. Next sentance.";
$words = preg_split( "/( )/", $string );
print_r($words);

$length = 0;
foreach($words as $word){
    $length += strlen($word);
}

$string_new = "";
$string_new2 = "";
$length_half = 0;
foreach($words as $word){
    $length_half += strlen($word);
    if($length_half >= ($length/2)){
        $string_new2 .= $word . ' ';
    }else{
        $string_new .= $word . ' ';
    }
}
echo '<br/><br/>';
echo 'Full=' . $string . '<br/>';
echo 'First=' . $string_new . '<br/>';
echo 'Second=' . $string_new2 . '<br/>';
echo 'First length=' . strlen($string_new) . '<br/>';
echo 'Second=' . strlen($string_new2) . '<br/>';
fico7489
  • 7,931
  • 7
  • 55
  • 89