I need a regex for my PHP script that will help me manipulate some strings using preg_replace.
For example, say I have the following string:
myvar = first_value AND var2 = second_value
I would like to have it converted to:
myvar = 'first_value' AND var2 = 'second_value'
However, I would also like to have it ignore when there is already a single quote around the value. So myvar = first_value AND var2 = 'second_value' will become myvar = 'first_value' AND var2 = 'second_value' and not myvar = 'first_value' AND var2 = ''second_value''.
I would also like it to deal with spaces within sub-strings when there is already a single quote around the value. So myvar = first_value AND var2 = 'second value' will become myvar = 'first_value' AND var2 = 'second value' and not myvar = 'first_value' AND var2 = 'second' value'.
NOTE: At no time will the string contain variable assignment with unquoted string values that have spaces in them i.e. myvar = first value is a scenario that will never arise. However, the string can contain any other character, even special characters e.g. myvar = &%$@_imspecial_* is totally valid.
The PHP Code I was working with looked something like below (#DontLaugh):
$col_clause_str = "myvar = first_value AND var2 = second_value";
$replace_pattern_str = '/([\w\@\-]+)\s*(\=|\>|\>\=|\<|\<\=)\s*\'{0,1}([\w\@\.\:\+\-\/\|\{\}\[\]\~\%\$\*\!]+)\'{0,1}/i';
$replace_str = '\1 \2 \'\3\'';
$col_clause_str = preg_replace($replace_pattern_str, $replace_str, $col_clause_str);
How can I improve this Regex?!
Thanks in advance.
EDIT:
I updated the question to be more descriptive.
You can replace this regex: –
with: –
Update: –
Ok, for your updated question, you can use this regex: –
And replace it with same string –
'\1'