Page 1 of 1

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

Posted: Wed Jun 13, 2007 2:39 pm
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 :(

Posted: Wed Jun 13, 2007 2:40 pm
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

Posted: Wed Jun 13, 2007 8:37 pm
by feyd
Look through my posts in the regex board. I've posted code that supports escaped quotes multiple times.

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

Posted: Thu Jun 14, 2007 4:01 am
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?

Posted: Thu Jun 14, 2007 8:00 am
by feyd
One of the more detailed ones: viewtopic.php?t=65940

You even posted in that one stereofrog. ;)

Posted: Thu Jun 14, 2007 11:07 am
by GeertDD

Code: Select all

/'((?:[^'\\]|\\.)*)'/s

Posted: Thu Jun 14, 2007 12:39 pm
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)

Posted: Thu Jun 14, 2007 12:54 pm
by GeertDD
This is what it should look like in PHP:

Code: Select all

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