SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Enthusiast
    Join Date
    Mar 2006
    Posts
    30
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    preg_match escape char

    I have a small problem with my preg_match.

    I want to get all string between % %.

    PHP Code:
    $text "%Test1%sdfsdfsdf%Test2%sdfsdfsdf%Test3\%%";

    preg_match_all("|%(.*)%|U"$text$outPREG_PATTERN_ORDER);

    echo 
    '<pre>';
    print_r($out);
    echo 
    '</pre>'
    This will return:
    - Test1
    - Test2
    - Test3\

    While I want it to return:
    - Test1
    - Test2
    - Test3\%

    So I need to match everything between % % not preceded by \.

    I've been trying with (?<!) but no luck.

    Help appreciated.

  2. #2
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Something like

    preg_match_all("~(?<!\\\\)%(.*?)(?<!\\\\)%~", $text, $out, PREG_PATTERN_ORDER);

    maybe

  3. #3
    SitePoint Guru aamonkey's Avatar
    Join Date
    Sep 2004
    Location
    kansas
    Posts
    953
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    this should work without negative look behind:
    PHP Code:
     preg_match_all("#%(.*(?:\\\%)*)%#U"$text$outPREG_PATTERN_ORDER); 

  4. #4
    Non-Member Gator99's Avatar
    Join Date
    Sep 2004
    Location
    Florida
    Posts
    613
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    With php preg you have to escape the backslash one extra time, ie instead of \\ its \\\

  5. #5
    SitePoint Enthusiast
    Join Date
    Mar 2006
    Posts
    30
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ah okay thanks.

    I tried escaping it \\ need to use it three times.

  6. #6
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Actually, three slashes is a php "feature" (bug), double escaping requires four slashes: \\\\. String parser deletes one pair, giving \\ and regexp engine strips off another one, leaving \.


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
  •