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
Related
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"]
I need to replace all double quotes in any (variable) given string.
For example:
$text = 'data-caption="hello"world">';
$pattern = '/data-caption="[[\s\S]*?"|(")]*?">/';
$output = preg_replace($pattern, '"', $text);
should result in:
"hello"world"
(The above pattern is my attempt at getting it to work)
The problem is that I don't now in advance if and how many double quotes are going to be in the string.
How can i replace the " with quot; ?
You may match strings between data-caption=" and "> and then replace all " inside that match with " using a mere str_replace:
$text = 'data-caption="<element attribute1="wert" attribute2="wert">Name</element>">';
$pattern = '/data-caption="\K.*?(?=">)/';
$output = preg_replace_callback($pattern, function($m) {
return str_replace('"', '"', $m[0]);
}, $text);
print_r($output);
// => data-caption="<element attribute1="wert" attribute2="wert">Name</element>">
See the PHP demo
Details
data-caption=" - starting delimiter
\K - match reset operator
.*? - any 0+ chars other than line break chars, as few as possible
(?=">) - a positive lookahead that requires the "> substring immediately to the right of the current location.
The match is passed to the anonymous function inside preg_replace_callback (accessible via $m[0]) and that is where it is possible to replace all " symbols in a convenient way.
This question already has an answer here:
Cannot work out a php str_replace() to remove comma [closed]
(1 answer)
Closed 2 years ago.
I have the following string:
Input:
$str = "I want to remove only comma from this string, how ?";
I want to remove commas from $str, I'm new in programming and I don't understand how regex works.
use str_replace.
Example
$str = "I want to remove only comma from this string, how ?";
$str = str_replace(",", "", $str);
Explaination
As you can see there is 3 arguments we pass in str_replace
"," => this one is what you want to replace
"" => this one is value that will replace first argument value. we pass blank so it will replace comma to blank
this one is string where you want to replace.
Regex: (?<!\d)\,(?!\d)
(\,|\.) for matching exact either , or .
(?!\d) should not contains digits ahead.
(?<!\d) should not contains digit behind.
PHP code:
<?php
$str = "I want to remove only comma from this string, how. ? Here comma and dot 55,44,100.6 shouldn't be removed";
echo preg_replace("/(?<!\d)(\,|\.)(?!\d)/", "", $str);
Output:
I want to remove only comma from this string how ? Here comma 55,44,100 shouldn't be removed
I need to know if there is any way to merge two regular expression into a single regexp. Recently I had to make the following php code but I feel that there is a simplified way to achieve this without using multiple preg_replace tags. What I am trying to do is strip off & © etc.. and to remove all multiple spaces
$textinput = 'this is a test input \' """""" """" ##$$%&*)_+!##$%^&*) 123 456';
$var = preg_replace("/&#?[a-z0-9]{2,8};/i",'',$textinput)
$string = preg_replace('/\s+/', ' ', $var);
output
this is a test input ' """""""""" ##$$%&*)_+!##$%^&*) 123 456
I am aware about the html_entity_decode function in php to strip the special characters off, well this just an example! How can I merge both of the regexp into a single one?
Thank you!
This will do your two replacements in one efficient step (without losing the whitespace character):
$replaced = preg_replace('~(?:&#?[a-z0-9]{2,8};)+|\s\K\s+~', '', $yourstring);
On the demo, see how all the extra characters are targeted.
Explanation
On the left side of the |, (?:&#?[a-z0-9]{2,8};)+ targets groups such as , not just one at a time but several together if they are touching.
On the right side, the \s matches one space, then the \K tells the engine to drop it from the match (it will not be replaced), then the \s+ matches any whitespace chars that follow
We replace with the empty string.
$var = preg_replace_callback('/&#?[a-z0-9]{2,8};|\s+/i', function($match) {
return $match[0][0] === '&' ? '' : ' ';
}, $textinput);
You could use a logical OR operator to combine both regexes,
(?:&#?[a-z0-9]{2,8};)+|(?<=\s)\s+
Your code would be,
<?php
$mystring = 'this is a test input \' """""" """" ##$$%&*)_+!##$%^&*) 123 456';
$pattern = "~(?:&#?[a-z0-9]{2,8};)+|(?<=\s)\s+~";
$replacement = "";
echo preg_replace($pattern, $replacement, $mystring);
?>
OR
<?php
$mystring = 'this is a test input \' """""" """" ##$$%&*)_+!##$%^&*) 123 456';
$pattern = "~&#?[a-z0-9]{2,8};|(?<=\s)\s+~";
$replacement = "";
echo preg_replace($pattern, $replacement, $mystring);
?>
output:
this is a test input ' """""" """" ##$$%&*)_+!##$%^&*) 123 456
I am after (if possible), a reg expression which will only replace questions marks "?" with "'" where it is not followed by the "=" symbol in my string?
e.g. this is something?, but this will remain?=forever
should end up as:
this is something', but this will remain?=forever
Thanks
Mu
This is simple using a negative lookahead: Use
\?(?!=)
Just check this.. Simple one without regex ( I don't know regex :( )...:p
$string = "this is something?, but this will remain?=forever";
$my_secret_replace = "THISISANYTHINGWHICHWILLNOTINSTRING_OR_ANYRANDOMNUMBER";
$temp_string = str_replace("?=",$my_secret_replace,$string);
$temp_string = str_replace("?","'",$temp_string);
$final_string = str_replace($my_secret_replace,"?=",$temp_string);
$string = "String contains ? and ?= contains too?=?";
echo preg_replace("/\?([^=]|$)/", "'\\1", $string);