简体   繁体   中英

Regex to add quotation marks to an unquoted expression

I'm trying to build a regex that will use preg_replace to quote the right side of an expression if it's unquoted.

So myvar = 3 becomes myvar = '3' . It should only deal with unquoted strings that are contiguous (so if there any spaces on the first string need be quoted eg myvar = 3 5 will become myvar = '3' 5 ).

I also want it to ignore any quoted string, so myvar = 'this is quoted' should not be modified.

So far I have the code below:

$str = 'myvar = 3';
$regex = '/([\w\@\-]+) *(\=|\>|\>\=|\<|\<\=) *([\w]+)/i';
$replace = '\1 \2 \'\3\'';
$result = preg_replace($regex, $replace_str, $str);

What do I need to put in $regex to make this work?

You could use preg_replace_callback, or maybe this could work (right side of the regex only):

#([^\\'\\"])(\\w+)([^\\'\\"])#

And replace like this:

$exp = '#([^\'\"])(\w+)([^\'\"])#';
$str = 'This is unquoted';
$quoted = preg_replace($exp, '\'$1$2$3\'', $str); // should hopefully be 'This is unquoted' after. Not tested.

It's kind of a hacky work-around though.

EDIT: Yeah, no-go. I'd recommend preg_replace_callback then.

I eventually settled for the following:

$str = 'myvar = 3';
$regex = '/([\w\@\-]+) *(\=|\>|\>\=|\<|\<\=) *([^\s\']+)/i';
$replace = '\1 \2 \'\3\'';
$result = preg_replace($regex, $replace_str, $str);

I needed this as one step of a multi-step operation so I wanted to use this regex in question to bake an uber regex that would do everything in one go. However, it turns out preg_replace can also be fed 'search' and 'replace' arrays, so I went with that for my final solution. It's much easier to grasp that way as well.

Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM