Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
PHP insert br tag after 2nd Word of a Given String

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;
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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;
over 4 years ago · Santiago Trujillo Report

0

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;
over 4 years ago · Santiago Trujillo Report

0

With preg_replace:

$new = preg_replace("/^(([^ ]+ ){2})/",'$1<br/>', $string);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!