SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Zealot
    Join Date
    May 2002
    Location
    RI-USA
    Posts
    113
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Remove Single Quotes (Regex)

    Hello,

    I'd like to know if there's a regular expression that will remove single quotes but keep them if they're surrounded by letters. Basically I'd like to turn this:

    'Tom's awesome pot roast'

    into

    Tom's awesome pot roast

    Any idea how I would do that? I tried
    PHP Code:
    [\b'\b] 
    but that replaces all single quotes. Thanks.
    Jim

  2. #2
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    How about this:
    PHP Code:
    preg_replace("/([^a-z])'(.*)'([^\s])/"'$1$2$3'"this is 'Tom's awesome pot roast'!"); 
    It removes pairs of quotes which aren't in situations that they could be abbreviations.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  3. #3
    @php.net Salathe's Avatar
    Join Date
    Dec 2004
    Location
    Edinburgh
    Posts
    1,397
    Mentioned
    64 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DigitalBurn View Post
    I'd like to know if there's a regular expression that will remove single quotes but keep them if they're surrounded by letters.
    I'm not sure if you're willing to delve into slightly more complex regular expressions but it's possible to write one which looks, in no uncertain terms, for the scenario you want: To remove single quotes only if they aren't surrounded by letters. One way of doing it would be to use the lookahead and lookbehind assertions to take a peek at what is surrounding the single quote character.

    The pattern: /'(?!(?<=[a-z]')(?=[a-z]))/i

    Translated to plain(ish) English: Match a single quote which is not: a) preceded by a letter and b) followed by a letter.

    Using that pattern, the $replacement value (2nd argument to preg_replace) could then just be an empty string "" as it should only ever match those quotes that you want to remove.
    Salathe
    Software Developer and PHP Manual Author.


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
  •