This question already has answers here:
How to fix associative array keys that lack single quotation marks in multiple files
(4 answers)
Closed 7 months ago.
I try to correct my PHP-code and add to the quotes ' around the keys of the arrays in my source-code.
I have like 10,000 files to correct. Can I use some regular expressions to achieve that?
I tried to use this regular expression, but it is not perfect:
\$([0-9a-zA-z_\-]+)\[([0-9a-zA-z_\-]+)\]\[([0-9a-zA-z_\-]+)\]
to
\$$1['$2']['$3']
Example of what I want to change:
$_SESSION[Name][name_2] to $_SESSION['Name']['name_2']
$_POST[Name][na-me_2] to $_SESSION['Name']['na-me_2']
$_GET[Name][na-me_2] to $_GET['Name']['na-me_2']
$tab[name_one] to $tab['name_one']
We can most likely capture our indices with a group, then preg_replace it, maybe with an expression similar to:
\[(.+?)\]
Test
$re = '/\[(.+?)\]/m';
$str = '$_SESSION[Name][name_2]
$_POST[Name][na-me_2]
$_GET[Name][na-me_2]
$tab[name_one]';
$subst = '[\'$1\']';
$result = preg_replace($re, $subst, $str);
echo $result;
RegEx
If this expression wasn't desired, it can be modified/changed in regex101.com.
RegEx Circuit
jex.im visualizes regular expressions:
If we wish to have more constraints, we can surely update this expression. For example, if we would have already had keys with ' or ", then we can just add a new boundary such as all chars except ' and " in a char class:
[^'"]*
and our expression would become:
\[([^'"]*?)\]
Demo
Test
$re = '/\[([^\'"]*?)\]/m';
$str = '$_SESSION[Name][name_2]
$_POST[Name][na-me_2]
$_GET[\'Name\'][na-me_2]
$tab[name_one]
$_POST[Name]["na-me_2"]
$_POST[\'Name\']["na-me_2"]';
$subst = '[\'$1\']';
$result = preg_replace($re, $subst, $str);
echo $result;
Output
$_SESSION['Name']['name_2']
$_POST['Name']['na-me_2']
$_GET['Name']['na-me_2']
$tab['name_one']
$_POST['Name']["na-me_2"]
$_POST['Name']["na-me_2"]
Related
I have a code like : 784XX . XX could be a character or number and I need an expression to remove the last 2 characters (XX) using ( and only ) preg_replace.
How can I do that?
For example, the output of :
782A3 is 782,
0012122 is 00121,
76542A is 7654,
333333CD is 333333,
You can use substr function.
But if you will use preg_replace you can do this:
$val = preg_replace('/[\w\d]{2}$/', '', $val);
I'm pretty sure there are much easier ways to do this task, yet if we wish to use regular expressions, we would be starting with just a simple expression such as:
(.+)?(..)
if I understand the problem right, and our desired output is in this capturing group:
(.+)
Demo
$re = '/(.+)?(..)/m';
$str = '782A3
0012122
76542A
333333CD';
$subst = '$1';
$result = preg_replace($re, $subst, $str);
echo $result;
RegEx Circuit
jex.im visualizes regular expressions:
Advice
AbraCadaver's advice in the comment is much better way:
substr('784XX', 0, -2);
I am using php to scrape a webpage and get this string:
'[{endTime:"2019-06-05T17:15:00.000+10:00",startTime:"2019-06-05T17:00:00.000+10:00"}]'
which is not valid json, the key names are encapsulated ...
I use preg_replace to create valid json:
$x = '[{endTime:"2019-06-05T17:15:00.000+10:00",startTime:"2019-06-05T17:00:00.000+10:00"}]'
$j = preg_replace('/(\w+)\s{0,1}:/', '"\1":', $x);
and get this value:
'[{"endTime":"2019-06-"05T17":"15":00.000+"10":00","startTime":"2019-06-"05T17":"00":00.000+"10":00"}]'
but I want this value:
'[{"endTime":"2019-06-05T17:15:00.000+10:00","startTime":"2019-06-05T17:00:00.000+10:00"}]'
How do I solve this problem?
RegEx 1
Your original expression seems to be find, we would just slightly modify that to:
([{,])(\w+)(\s+)?:
and it might work, we are adding a left boundary:
([{,])
and a right boundary:
:
and our key attribute is in this capturing group:
(\w+)
RegEx 2
We can expand our first expression to:
([{,])(\s+)?(\w+)(\s+)?:
in case, we might be having spaces before the key attribute:
Demo
Test 1
$re = '/([{,])(\w+)(\s+)?:/m';
$x = '[{endTime:"2019-06-05T17:15:00.000+10:00",startTime:"2019-06-05T17:00:00.000+10:00"}]';
$subst = '$1"$2":';
$result = preg_replace($re, $subst, $x);
echo $result;
Test 2
$re = '/([{,])(\s+)?(\w+)(\s+)?:/m';
$x = '[{endTime:"2019-06-05T17:15:00.000+10:00",startTime:"2019-06-05T17:00:00.000+10:00"}]';
$subst = '$1"$3":';
$result = preg_replace($re, $subst, $x);
echo $result;
Output
[{"endTime":"2019-06-05T17:15:00.000+10:00","startTime":"2019-06-05T17:00:00.000+10:00"}]
Demo
RegEx Circuit
jex.im visualizes regular expressions:
use this pattern :
([{,])([^:]+):
it will find all texts which are following by { or ,
and use this for replacement:
$1"$2":
It will add a doublequote on both sides of your word.
This question already has answers here:
What is the difference between .*? and .* regular expressions?
(3 answers)
Closed 4 years ago.
I have a string:
$str = '{:de}Hallo Welt{:}{:en}Helo world{:}';
now i need to get substring for setted language.
$placeholder = '{:en}';
$lang_content = preg_replace('/(.*)'.preg_quote($placeholder).'(.*)'.preg_quote('{:}').'(.*)/sm', '\2', $str);
in case of value for placeholder {:en} i get Helo world as value for $lang_content, it works fine, but in case {:de} i get Hallo Welt{:}{:en}Helo world.
How can it be fixed? thanx!
You need to make the regex lazy by adding a ? in the second capture.
$str = '{:de}Hallo Welt{:}{:en}Helo world{:}';
$placeholder = '{:de}';
$lang_content = preg_replace('/(.*)'.preg_quote($placeholder).'(.*?)'.preg_quote('{:}').'(.*)/sm', '\2', $str);
echo $lang_content; // Hallo Welt
https://3v4l.org/m6AGF
An optional method would be to use preg_match to get an associative array.
$str = '{:de}Hallo Welt{:}{:en}Helo world{:}';
preg_match_all("/\{:(.*?)}(.*?)\{/", $str, $matches);
$matches = array_combine($matches[1], $matches[2]);
var_dump($matches);
echo $matches["de"]; // Hallo Welt
https://3v4l.org/ELB2B
With the Ungreedy flag (U).
You can update the flags at the end of your regex from /sm to /smU for the result to stop at the next occurrence of {:} in the string and not at the last one.
If the string is to contain several occurrences, maybe you can also add the global (g) flag so the regex doesn't stop after the first one.
You can test it here: https://regex101.com/r/4XSPoz/3
By the way, it seems that your are using preg_replace as a way to find a substring and don't actually need to replace it in the result, maybe you should use preg_match instead.
This question already has answers here:
How can I get a substring located between 2 quotes?
(3 answers)
Closed 4 years ago.
I have this text :
$txt1 = "aaa'bbb'ccc'ddd''eee'fff";
And I would want to keep that :
"aaacccfff"
But when I use that :
$txt2 = preg_replace ( #\'.+\'# , "" , $txt1);
I obtain ça.
$txt2 == "aaafff"
(I lost "ccc" in the batlle)
thank of your help
You could use the str_replace
$txt1 = "aaa'bbb'ccc'ddd''eee'fff";
$txt = str_replace("'", "", $txt1);
echo $txt;
This is what you need to replace characters between single quotes ''. Demo https://eval.in/997294
Here,
' matches the character ' literally
[^'] Match a single character but not '
+ Quantifier — Matches between one and unlimited times
' matches the character ' literally
So using the above regex you just match the patterns and finally replace those characters inside single quotes(') with ''
<?php
$re = "/'[^']+'/";
$str = "aaa'bbb'ccc'ddd''eee'fff";
$subst = '';
$result = preg_replace($re, $subst, $str);
echo $result;
?>
Program Output
aaacccfff
regexes are greedy by default, this means they matches the longest possible match.
Your regex matches 'bbb'ccc'ddd''eee' and replaces it with nothing.
in your case you have to use the lazy variant using the ? operator to get the shortestest possible match,e.g.
$txt2 = preg_replace ( '/\'.+?\'/' , "" , $txt1);
Live example: http://rextester.com/LUGY72388
for greedy/lazy of regexes see e.g. http://www.rexegg.com/regex-quantifiers.html#greedy
I'm looking for a RegEx for preg_replace in PHP for the following scenario:
example string "Bjerre- Jonas, Jorgensen- Silas, Wohlert- Johan, Madsen- Bo"
desired string "Jonas Bjerre, Silas Jorgensen, Johan Wohlert, Bo Madsen"
string is a csv field and double quotes are enclosures and are part of string
any number of occurrences may exist including none - the example clearly has 4
there is a consistent - to match on separating matches to be swapped
I'm a noob at PHP and RegEx and have been playing around in the cool test arena with things like preg_replace("/^\"(?<=- )/", ""$2 $1$3"", $input_lines); with horrible results. Thanks for help!
([^," -]*)\s*-\s*([^," ]*)
Try this.See demo.
http://regex101.com/r/hI0qP0/20
$re = "/([^\", -]*)\\s*-\\s*([^,\" ]*)/m";
$str = "\"Bjerre- Jonas, Jorgensen- Silas, Wohlert- Johan, Madsen- Bo\"";
$subst = "$2 $1";
$result = preg_replace($re, $subst, $str);