SitePoint Sponsor |
|
User Tag List
Results 1 to 3 of 3
Thread: Remove Single Quotes (Regex)
-
Jul 31, 2009, 07:42 #1
- 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 triedPHP Code:[\b'\b]
Jim
-
Jul 31, 2009, 07:53 #2
- 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'!");
Jake Arkinstall
"Sometimes you don't need to reinvent the wheel;
Sometimes its enough to make that wheel more rounded"-Molona
-
Jul 31, 2009, 10:40 #3
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.
Bookmarks