Replace stuff inside the quotes but not if it's escaped

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Replace stuff inside the quotes but not if it's escaped

Post by Grim... »

Hello, I need regex help again :(

I want to replace anything that's inside single quotes, ignoring escaped quotes.

To clarify:

Code: Select all

This is a 'very' hot day
would become

Code: Select all

this is a 'something else' hot day
and

Code: Select all

'I can\'t believe it'
would becode

Code: Select all

'something else'
I've got

Code: Select all

$q = preg_replace("/'.*?'/s", "'something else'", $q);
but now I'm stuck :(
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Post by Grim... »

Oh, and it's got to be non-greedy too, so if I have

Code: Select all

I 'think' I can 'do' it
I need

Code: Select all

I 'something else' I can 'something else' it
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Look through my posts in the regex board. I've posted code that supports escaped quotes multiple times.
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Re: Replace stuff inside the quotes but not if it's escaped

Post by stereofrog »

Grim... wrote:Hello, I need regex help again :(

I want to replace anything that's inside single quotes, ignoring escaped quotes.
How about

Code: Select all

$regexp = "/
	'  # open quote
	
		(
			(\\\\ .) # slash + character
			|        # or
			.        # just a character
		)* # many times

	'  # close quote
/x";
@feyd, didn't find your post(s), care to post the link or your expr?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

One of the more detailed ones: viewtopic.php?t=65940

You even posted in that one stereofrog. ;)
User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

Post by GeertDD »

Code: Select all

/'((?:[^'\\]|\\.)*)'/s
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post by stereofrog »

feyd wrote:One of the more detailed ones: viewtopic.php?t=65940

You even posted in that one stereofrog. ;)
Ah, thanks! ;)
GeertDD wrote:

Code: Select all

/'((?:[^'\\]|\\.)*)'/s
Not a valid regexp in php (think of slash doubling)
User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

Post by GeertDD »

This is what it should look like in PHP:

Code: Select all

preg_match_all('/\'((?:[^\'\\\]|\\\.)*)\'/s', "I 'think' I 'can\'t'.", $m);
Post Reply