0

I want to divide words in string by equal parts and then add something in middle.

$string = "hello i am superman and also batman";
$insert = "word";

so i want the result to be

$result= "hello i am superman word and also batman";

What i tried...but below code is very dirty...any easy method please ?

$word = "word";
$arr = explode(" ",$string);
$count = round(sizeof($arr)/2);
$i=0;
foreach($arr as $ok)
{

if($i == $count)
{
$new.=$ok." ".$word;
}
else
{
$new.= $ok." ";
}
$i++;
}

echo trim($new);
Vishnu
  • 2,372
  • 6
  • 36
  • 58

2 Answers2

1

You can use array_splice. An example below:

$string = "hello i am superman and also batman";
$insert = "word";

$string_array = explode(' ',$string);

array_splice( $string_array, round(count($string_array)/2), 0, array($insert) );

echo implode(' ', $string_array);

Or use it as a function:

function insertString($string, $insert){

    $string_array = explode(' ',$string);

    array_splice( $string_array, round(count($string_array)/2), 0, array($insert) );

    return implode(' ', $string_array);

}

echo insertString('hello i am superman and also batman','word');

Output will be:

hello i am superman word and also batman
vicente
  • 2,613
  • 4
  • 22
  • 27
1

This is practically quite simple as long as you can accept a little lenience of splitting the string into "equal parts." In this scenario, I am considering the character count instead of the number of words. Use strpos to determine the position of the first space after the "halfway" point of the string:

$insertPoint = strpos($string, ' ', strlen($string) / 2);

Then inject the word there! (Used this SO answer to achieve this)

$new = substr_replace($string, ' '.$insert, $insertPoint, 0);
Community
  • 1
  • 1
sjagr
  • 15,983
  • 5
  • 40
  • 67