I’m trying to insert <br/> tag after 2nd word of a given string, but it crops some words of my string, can anyone help to fix the code on this
$pos = 1;
$string = 'Lorem Imsem Dollar Country';
$words = explode(" ", $string);
$new_array = array_slice($words, 0, $pos, true) +
array($pos => '<br/>') +
array_slice($words, $pos, count($words) - 1, true) ;
$new_string = join(" ",$new_array);
echo $new_string;
Advertisement
Answer
You can use array_splice :
$pos = 1;
$string = 'Lorem Imsem Dollar Country';
$words = explode(" ", $string);
array_splice( $words, $pos, 0, '<br>' );
$new_string = join(" ",$words);
echo $new_string;