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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With