SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2004
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Need help with regex

    Supposed I have a string like this:
    Code:
    bla bla {strong} bla bla bla {bold} bla bla
    How to get {strong} and {bold} using regex? I've already tried:
    Code:
    /\{.*\}/
    but the result is:
    Code:
    {strong} bla bla bla {bold}

  2. #2
    SitePoint Addict
    Join Date
    Jul 2006
    Location
    Kansas City, MO
    Posts
    280
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    /\{.*?\}/

  3. #3
    SitePoint Enthusiast
    Join Date
    Oct 2004
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ah okay, thanks... lol, why I missed that one

    actually I'm working for something like:
    Code:
    bla bla {{strong} bla} bla bla {bold} bla bla
    so it's nested, and I need this result:
    Code:
    {{strong} bla}
    {strong}
    {bold}
    can I only use regex? I'm thinking to create recursive function

  4. #4
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Simple iteration would be enough

    PHP Code:
    $s 'bla bla {{stro{ng}} bla} bla bla {b{o}ld}bla bla';
    $re '/\{([^{}]*)\}/e';

    while(
    preg_match($re$s))
        
    $s preg_replace($re'$matches[]="$1"'$s);

    print_r($matches); 

  5. #5
    SitePoint Enthusiast
    Join Date
    Oct 2004
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That's cool simple solution stereofrog!
    Darn... I'm too late seeing your reply here, I have already made a recursive function, it's more complicated lol.
    Btw, I want to have '\{' and '\}' not being translated, how to tell regex to ignore that?

    For example:
    Code:
    bla \{bla\} {{strong} bla} bla bla {bold} bla bla
    and the result is the same with above while '\{bla\}' is not selected.

    thanks.

  6. #6
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    To handle escapes, change bounding \{'s to (?<!\\\\)\{ , inner group should be something like ((\\\\.|[^{}])*).

  7. #7
    SitePoint Enthusiast
    Join Date
    Oct 2004
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ok thanks, will try it..


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •