Regex not displaying well whe using PHP preg_quote - php

Hi Im trying to concatinate a string before converting that string into regex in PHP, but the problem is it's not displaying as expected. I've been searching using google and found out about preg_quote, problem is it's not working well.
Here is my example:
$mystring = "banana"; // put this to a variable assume this value is dynamic
$regex_str = "/^"$mystring"\-[a-z0-9]\-[a-z0-9]$/";
//Im expecting expecting /^banana\-[a-z0-9]\-[a-z0-9]$/
$regex = preg_quote($regex_str);
but what I am getting is:
/\^banana\\\-\[a\-z0\-9\]\\\-\[a\-z0\-9\]\$/
and always returning the wrong value.

Call preg_quote() on the string you're adding before you add it into the regex:
$mystring = "banana";
$regex_str = "/^" . preg_quote($mystring, "/") . "\-[a-z0-9]\-[a-z0-9]$/";

Related

Looking for assistance trying to understand a strange scenario where `preg_replace` won't work as expected

So I have these 3 strings:
$campaignId = 'br_B081D4LCMX_v2';
$adgroupId = '006_B081D4LCMX_{{adgroupQS}}';
$creativeId = '';
And the following string
$url = '?maas=maas_adg_api_587443019484609215_static_9_51&ref_=aa_maas&aa_campaignid={insertCampaign}&aa_adgroupid={insertAdGroupId}&aa_creativeid={insertCreativeId}';
I am trying to replace all what's inside {} by the correspondent variable.
I tried this:
$url = preg_replace([
'/(aa_campaignid=)[^&]+/',
'/(aa_adgroupid=)[^&]+/',
'/(aa_creativeid=).+/'
], [
'$1' . $campaignId, // Tried with "$1{$campaignId}" too
'$1' . $adgroupId,
'$1' . $creativeId
], $url);
And I expected the following result:
?maas=maas_adg_api_587443019484609215_static_9_51&ref_=aa_maas&aa_campaignid=br_B081D4LCMX_v2&aa_adgroupid=006_B081D4LCMX_{{adgroupQS}}&aa_creativeid=
But I obtained this instead
?maas=maas_adg_api_587443019484609215_static_9_51&ref_=aa_maas&aa_campaignid=br_B081D4LCMX_v2&06_B081D4LCMX_{{adgroupQS}}&aa_creativeid=
For some reason aa_adgroupid is completely replaced instead of using the group $1 obtained from the regexp.
When I updated my code to use preg_replace_callback instead of preg_replace, it worked perfectly.
Here is the code for reference
$replacements = [
$campaignId,
$adgroupId,
$creativeId
];
$url = preg_replace_callback([
'/(aa_campaignid=)[^&]+/',
'/(aa_adgroupid=)[^&]+/',
'/(aa_creativeid=).+/'
], function ($matches) use (&$replacements) {
return $matches[1] . array_shift($replacements);
}, $url);
Same regular expressions, same string, same "position" (assuming matches[1] should be the same as $1 in my previous example)
The solution to the problem with my first example may be in front of my eyes but I am not being able to find it despite I spent hours looking at it and trying different options.
Does anyone sees anything wrong with it? Any idea why it is not working as expected?
You need to use
'${1}' . $adgroupId
or else your replacement ends up as
$1006_B081D4LCMX_{{adgroupQS}}
and capture group #10 does not exist.
Hence, why you end up with:
&06_B081D4LCMX_{{adgroupQS}}
and the leading zero is missing.
It's not enough to merely understand PHP variable interpolation, you have to remember that certain characters and syntaxes have special meaning in BOTH regex expressions and the replacement string.
You've avoided the issue via preg_replace_callback() because you're accessing $matches[1] and not $matches[10].

How to replace string from getting postman as parameter

Currently i am facing issue of replace string , I used postman & passing string in postman like [{"id":"115","flag":"1","qty":"3","size":"10"}] as a parameters but when i print string i am getting output like [{\"id\":\"115\",\"flag\":\"1\",\"qty\":\"3\",\"size\":\"10\"}] , So i want to only remove '\' from string i have tried following code but not work.
$fliesid_in_store = $_REQUEST['fliesid_in_store'];
echo $res = preg_replace("/[^a-zA-Z]/", "", $fliesid_in_store);
Have you tried stripslashes.
$fliesid_in_store = $_REQUEST['fliesid_in_store'];
echo stripslashes($fliesid_in_store);
The string you mentioned is in json format
$json = [{"id":"115","flag":"1","qty":"3","size":"10"}] //this is json
Assign that to variable and decode it.
$string = json_decode($json,TRUE) this give result in array format
In your case
$string = json_decode($_REQUEST['fliesid_in_store'],TRUE);

How to change integer value in preg_match PHP?

sorry if my question was stupid, please someone help me to fix this issue.
i have string like
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/";
this $str_value is dynamic , it will change each page. now i need to replace 9 in this string as 10. add integer 1 and replace
for example if the $str_value = "http://99.99.99.99/var/test/src/158-of-box.html/251/"
then output should be
http://99.99.99.99/var/test/src/158-of-box.html/252/
i tried to replace using preg_match but i m getting wrong please somesone help me
$str = preg_replace('/[\/\d+\/]/', '10',$str_value );
$str = preg_replace('/[\/\d+\/]/', '[\/\d+\/]+1',$str_value );
Thank's for the answer, #Calimero! You've been faster than me, but I would like to post my answer, too ;-)
Another possibilty is to fetch the integer by using a group. So you don't need to trim $matches[0] to remove the slashes.
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/";
$str = preg_replace_callback('/\/([\d+])\//', function($matches) {
return '/'.($matches[1]+1).'/';
}, $str_value);
echo $str;
You need to use a callback to increment the value, it cannot be done directly in the regular expression itself, like so :
$lnk= "http://99.99.99.99/var/test/src/158-of-box.html/9/";
$lnk= preg_replace_callback("#/\\d+/#",function($matches){return "/".(trim($matches[0],"/")+1)."/";},$lnk); // http://99.99.99.99/var/test/src/158-of-box.html/10/
Basically, the regexp will capture a pure integer number enclosed by slashes, pass it along to the callback function which will purge the integer value, increment it, then return it for replacement with padded slashes on each side.
I'd suggest also another approach based on explode and implode instead of doing any regexp stuff. In my opinion this is more readable.
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/11/";
// explode the initial value by '/'
$explodedArray = explode('/', $str_value);
// get the position of the page number
$targetIndex = count($explodedArray) - 2;
// increment the value
$explodedArray[$targetIndex]++;
// implode back the original string
$new_str_value = implode('/', $explodedArray);

I need to get a value in PHP "preg_match_all" - Basic (I think)

I am trying to use a License PHP System…
I will like to show the status of their license to the users.
The license Server gives me this:
name=Service_Name;nextduedate=2013-02-25;status=Active
I need to have separated the data like this:
$name = “Service_Name”;
$nextduedate = “2013-02-25”;
$status = “Active”;
I have 2 days tring to resolve this problem with preg_match_all but i cant :(
This is basically a query string if you replace ; with &. You can try parse_str() like this:
$string = 'name=Service_Name;nextduedate=2013-02-25;status=Active';
parse_str(str_replace(';', '&', $string));
echo $name; // Service_Name
echo $nextduedate; // 2013-02-25
echo $status; // Active
This can rather simply be solved without regex. The use of explode() will help you.
$str = "name=Service_Name;nextduedate=2013-02-25;status=Active";
$split = explode(";", $str);
$structure = array();
foreach ($split as $element) {
$element = explode("=", $element);
$$element[0] = $element[1];
}
var_dump($name);
Though I urge you to use an array instead. Far more readable than inventing variables that didn't exist and are not explicitly declared.
It sounds like you just want to break the text down into separate lines along the semicolons, add a dollar sign at the front and then add spaces and quotes. I'm not sure you can do that in one step with a regular expression (or at least I don't want to think about what that regular expression would look like), but you can do it over multiple steps.
Use preg_split() to split the string into an array along the
semicolons.
Loop over the array.
Use str_replace to replace each '=' with ' = "'.
Use string concatenation to add a $ to the front and a "; to the end of each string.
That should work, assuming your data doesn't include quotes, equal signs, semicolons, etc. within the data. If it does, you'll have to figure out the parsing rules for that.

PHP Split a string with start and stop value

I have fooled around with regex but can't seem to get it to work. I have a file called includes/header.php I am converting the file into one big string so that I can pull out a certain portion of the code to paste in the html of my document.
$str = file_get_contents('includes/header.php');
From here I am trying to get return only the string that starts with <ul class="home"> and ends with </ul>
try as I may to figure out an expression I am still confused.
Once I trim down the string I can just print that on my page but I can't figure out the trimming part
If you need something really hardcore, http://www.php.net/manual/en/book.xmlreader.php.
If you just want to rip out the text that fits that pattern try something like this.
$string = "stuff<ul class=\"home\">alsdkjflaskdvlsakmdf<another></another></ul>stuff";
if( preg_match( '/<ul class="home">(.*)<\/ul>/', $string, $match ) ) {
//do stuff with $match[0]
}
I'm assuming that the difficulty you're having has to do with escaping the regex special characters in the string(s) you're using as a delimiter. If so, try using the preg_quote() function:
$start = preg_quote('<ul class="home">');
$end = preg_quote('</ul>', '/');
preg_match("/" . $start. '.*' . $end . "/", $str, $matching_html_snippets);
The html you want should be in $matching_html_snippets[0]
You probably want an XML parser such as the built in one. Here is an example you might want to take a look at.
http://www.php.net/manual/en/function.xml-parse.php#90733
If you want to use regex then something along the lines of
$str = file_get_contents('includes/header.php');
$matchedstr = preg_match("<place your pattern here>", $str, $matches);
You probably want the pattern
'/<ul class="home">.*?<\/ul>/s'
Where $matches will contain an array of the matches it found so you can grab whatever element you want from the array with
$matchedstr[0];
which will return the first element. And then output that.
But I'd be a bit wary, regular expressions do tend to match to surprising edge cases and you need to feed them actual data to get reliable results as to when they are failing. However if you are just passing templates it should be ok, just do some tests and see if it all works. If not I'd still recommend using the PHP XML Parser.
Hope that helps.
If you feel like not using regexes you could use string finding, which I think the PHP manual implies is quicker:
function substrstr($orig, $startText, $endText) {
//get first occurrence of the start string
$start = strpos($orig, $startText);
//get last occurrence of the end string
$end = strrpos($orig, $endText);
if($start === FALSE || $end === FALSE)
return $orig;
$start++;
$length = $end - $start;
return substr($orig, $start, $length);
}
$substr = substrstr($string, '<ul class="home">', '</ul>');
You'll need to make some adjustments if you want to include the terminating strings in the output, but that should get you started!
Here's a novel way to do it; I make no guarantees about this technique's robustness or performance, other than it does work for the example given:
$prefix = '<ul class="home">';
$suffix = '</ul>';
$result = $prefix . array_shift(explode($suffix, array_pop(explode($prefix, $str)))) . $suffix;

Categories