Jump to content

[SOLVED] regex for quoted text within a string


abazoskib

Recommended Posts

I am still getting the hang of regex expressions, but I cant seem to figure out how I would escape quoted text within a string. The qualitifcations for escaping them would be to have [a space] [a double quote] [any text] [a double quote] [a space] but there cant be anything besides a space before and after, not even a newline.

 

here's what i have so far:

 

$pattern = '/ "." /';
$replacement = '/ \".\" /';
$val =  preg_replace($pattern, $replacement, $val);

 

But it's not working. I've always wanted to learn how to use regular expressions and like I said I am new to them.

That won't work simshaun. The '*' by itself is greedy and will match the text between the very first and very last double quote instead of matching multiple quoted strings when they exist. Plus it REMOVED the quoted text entirely instead of just escaping the double quote marks.

 

$val = 'Here is "quote number one" and here is "quote number two" with a space';

$pattern = '/\s\"(.*?)\"\s/';
$replacement = ' \\\"\1\\\" ';
$val =  preg_replace($pattern, $replacement, $val);
echo $val;

//output:
// Here is \"quote number one\" and here is \"quote number two\" with a space

That won't work simshaun. The '*' by itself is greedy and will match the text between the very first and very last double quote instead of matching multiple quoted strings when they exist.

Yes, I should have made it nongreedy, but the entire logic is flawed in the first place.

 

What if the string is ended with quoted text? Is it not supposed to be escaped as well?

 

Plus it REMOVED the quoted text entirely instead of just escaping the double quote marks.
You must have looked at it roughly 10 or 20 seconds after I posted, because I fixed it shortly after posting.

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.