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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.