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

185
Vistas
Regular Expressions If Else

I have a string: /foo/{bar}/{baz?}

Now i want to extract all words inside the {...}. But on the word with the "?" i want to select not only the {...} but also the "/" before "{"

So far i got this:

$string = '/foo/{bar}/{baz?}';

preg_match_all('~{(\w+)[?]?}~', $string, $matches);
print_r($matches);

Result:

Array
(
    [0] => Array
        (
            [0] => {bar}
            [1] => {baz?}
        )

    [1] => Array
        (
            [0] => bar
            [1] => baz
        )

)

But should be:

Array
(
    [0] => Array
        (
            [0] => {bar}
            [1] => /{baz?}
        )

    [1] => Array
        (
            [0] => bar
            [1] => baz
        )

)

(Notice the / before the {baz?} match)

Hope this is clear enough my english is not so good. Thanks

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Use a branch reset group ((?|...|...)) with 2 capturing groups inside that will share the same ID:

/(?|\/{(\w+)\?}|{(\w+)})/

See the regex demo

Details:

  • (?| - branch reset group start
  • \/{(\w+)\?} - a /{, then 1+ word chars (captured into Group 1) and then ?}
  • | - or
  • {(\w+)}) - a { followed with 1+ word chars (captured into Group 1 again) and then }.

PHP demo:

$re = '/(?|\/{(\w+)\?}|{(\w+)})/';
$str = '/foo/{bar}/{baz?}';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
print_r($matches);
about 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