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;
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;
With $pos you can select the position of the <br/> tag.
Use $pos = 2 to add the tag after second position
$pos = 2;
$string = 'Lorem Imsem Dollar Country';
$words = explode(" ", $string);
array_splice( $words, $pos, 0, '<br>' );
$new_string = join(" ",$words);
echo $new_string;
With preg_replace:
$new = preg_replace("/^(([^ ]+ ){2})/",'$1<br/>', $string);