Split a string into two parts of equal length using PHP

I need to split a string into two parts of equal length. String can contain spaces, commas or anything. I mentioned and tried the example code for the explode expression from the link http://www.testingbrain.com/php-tutorial/php-explode-split-a-string-by-string-into-array.html , but there it does not display a sample for division into equal length.

One more thing, while word splitting should not be broken.

+4
source share
4 answers

here you go.

$str="Test string";
$middle=strlen($str)/2;
$first=substr($str,0,$middle);
$last=substr($str,$middle);
+2
source

, , , (,, ., @ ..)

$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);
+2

A good start, but the original specification should be a little refined, as for any chain with an odd length, which is simply not possible! This suggests that if you change the specification to approximately equal length, I would analyze if the half -1 symbol is not alphabetic, if it is cut there, if it identifies the previous and next places in space in alphabetical order and cuts closer to half

0
source

I think this is a 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/>';
0
source

Source: https://habr.com/ru/post/1612032/


All Articles