Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

246
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda