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

249
Visualizações
PHP preg_replace second occurence of character

How do I adjust my code below to replace the second » character using preg_replace?

$out = 'Home » Food » Fruit';
$out = preg_replace('/»/', 'Category:', $out, 1);

Thanks in advance!

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

To only remove the second occurrence of a string, you need to match the first one, and then match and capture all text up to the second one, and then replace using a backreference.

Use

$out = 'Home » Food » Fruit';
$out = preg_replace('/(»[^»]*)»/', '$1Category:', $out, 1);
echo $out;

See the PHP demo. The last $limit argument will have preg_replace only replace the first match.

Details:

  • (»[^»]*) - Capturing group #1 matching
    • » - a literal »
    • [^»]* - 0+ occurrences (due to * quantifier) of any chars other than »
  • » - a literal »

See the regex demo.

A variation that is only supported in Boost/PCRE (and latest versions of Onigmo) and will also work for you:

/»[^»]*\K»/

See another regex demo. \K will discard all the text matched so far in the current iteration. so you will only have the closing chevron in the match to be replaced with your replacement 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