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

184
Views
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 answers
Answer question

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 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!