Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

With preg_replace:

$new = preg_replace("/^(([^ ]+ ){2})/",'$1<br/>', $string);
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda