SitePoint Sponsor

User Tag List

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

    regexp - capitalize each word when contained in quotes

    I'm trying to write a regexp-based text formatter - the data I'm parsing is all caps & I'm trying to spare my site visitors the pain. The part I'm stuck on is I want to capitalize all words inside quotes that appear after a [digit][comma][space]. Example:

    Some text 9999, "capitalize each word here" more text "not capitalized".

    ...should be modified to...

    Some text 9999, "Capitalize Each Word Here" more text "not capitalized".

    I can't grasp the logic to write an regexp for this. Tried lookaheads, lookbehinds, setting laziness & can't figure out what I need to match each individual word inside the quotes so I can \u each match.

    A (regexp) solution or even just pointers would be much appreciated.

  2. #2
    SitePoint Member
    Join Date
    Apr 2006
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    most simple approach would be this:
    1. write a function UcWords with a preg_replace that replaces first character of every word in a string
    2. use preg_replace with modifier /e and a call to that function

  3. #3
    SitePoint Wizard silver trophy
    Join Date
    Mar 2006
    Posts
    6,132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    think this should work
    PHP Code:
    $s 'Some text 9999, "capitalize each word here" more text "not capitalized".';
    $p '#(\d+), "([^"]+)"#e';
    $r "'\\1, \"'.ucwords(strtolower('\\2')).'\"'";

    echo 
    preg_replace($p$r$s); 

  4. #4
    Obey the Purebreed trib4lmaniac's Avatar
    Join Date
    Dec 2004
    Location
    Cornwall, UK
    Posts
    594
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Basically the same thing but looking a bit friendlier:
    PHP Code:
    $text preg_replace('/(?<=\d, ")[^"]+/e'"ucwords('$0')"$text); 

  5. #5
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    For phpsourcerer's first post, he went dredging in the archives. Your work is for naught as it is highly unlikely autobeef has been patiently waiting for a solution all this time.

  6. #6
    Obey the Purebreed trib4lmaniac's Avatar
    Join Date
    Dec 2004
    Location
    Cornwall, UK
    Posts
    594
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Perhaps it is our fault for not noticing the error above the posting form.
    Note: This thread is more than 1 month old. Please consider creating a new thread instead.


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
  •