John Davidson

arrays - PHP insert br tag after 2nd Word of a Given String

0 comments
Message:


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;


My Answer:
a
tag after the 2nd word of a given string in PHP. Here's a simple example of how you can achieve this using PHP:

php
$string = "This is a sample string";

// Split the string into an array of words
$words = explode(" ", $string);

// Insert
tag after the 2nd word
array_splice($words, 2, 0, "
");

// Join the array back into a string
$newString = implode(" ", $words);

echo $newString;


This code will output:

This is
a sample string


You can modify the input string and customize the position where you want to insert the
tag by changing the index in the `array_splice` function.

Rate this post

3 of 5 based on 7560 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us