How to remove certain Part of JSON - php

Sorry for my bad English in Advance. Here is my JSON return.
https://images-na.ssl-images-amazon.com/images/M/MV5BYzc3OGZjYWQtZGFkMy00YTNlLWE5NDYtMTRkNTNjODc2MjllXkEyXkFqcGdeQXVyNjExODE1MDc#._V1_UY268_CR5,0,182,268_AL_.jpg
How can I remove the part UY268_CR5,0,182,268_AL_. Specifically that part only. And I have many of this links. Each having different strings there. For example:
https://m.media-amazon.com/images/M/MV5BYWNlMWMxOWYtZWI0Mi00ZTg0LWEwZTMtZTEzZDY0NzAxYTA4XkEyXkFqcGdeQXVyMTQxNzMzNDI#._V1_UX182_CR0,0,182,268_AL_.jpg
As shown it is different. I want to remove the part UX182_CR0,0,182,268_AL_. Each of the results I have has almost the same structure but the end part I want to remove. I am on laravel and so I am encoding my jsons result from controller. Is there anyone this can be done with php?
Update:
Here is the code I tried.
$json = json_decode($data,true);
$slice = str_replace("UY268_CR5,0,182,268_AL_","", $json);
return $slice ['poster'];
The string is removed but what about different strings with different URL's like mentioned above?

You can try with preg_replace() with the combination of lookahead and lookbehind
<?php
$re = '/(?<=_V1_)(.+?)(?=.jpg)/';
$str = 'https://m.media-amazon.com/images/M/MV5BYWNlMWMxOWYtZWI0Mi00ZTg0LWEwZTMtZTEzZDY0NzAxYTA4XkEyXkFqcGdeQXVyMTQxNzMzNDI#._V1_UX182_CR0,0,182,268_AL_.jpg';
$subst = '';
$result = preg_replace($re, $subst, $str, 1);
echo "The result of the substitution is ".$result;
?>
DEMO: https://eval.in/1044470
REFF: Regex lookahead, lookbehind and atomic groups
REGEX EXPLANATION: https://regex101.com/r/aHAw5f/1

Related

PHP: How to preg_split by full stop?

I want to take a string and split it (or explode it) into an array by full-stops (periods).
I used to have:
$processed_data = explode(".", $raw_data);
but this removes the full-stop.
Researching, I found preg_split, so tried:
$processed_data = preg_split('\.', $raw_data, PREG_SPLIT_DELIM_CAPTURE);
with both \. and \\.
but try as I might, I cannot find a way to properly include the full-stop.
Would anyone know the right way to do this?
The expected result is:
The string
$raw_data = 'This is my house. This is my car. This is my dog.';
Is broken into an array by full-stop, eg:
array("This is my house.", "This is my car.", "This is my dog.")
To split a string into sentences:
preg_match_all('~\s*\K[^.!?]*[.!?]+~', $raw_data, $matches);
$processed_data = $matches[0];
Note: if you want to handle edge cases like abbreviations, a simple regex doesn't suffice, you need to use nltk or any other nlp tool with a dictionary.
Can you try this.
$string = preg_replace("/\.\s?([A-Z])/", "*****$1", $raw_data);
$array = explode("*****", $string);

PHP: replace text in the last brackets in string

i thinking how can I replacing last item of form names like this:
content[1]
content[1][officeImage]
content[2][officeImage]
content[3][something][officeImage]
...
Depth of "array" can be infinity and I need replace last of him like this:
content[replaced]
content[1][replaced]
content[2][replaced]
content[3][something][replaced]
...
Is here someone who can write preg_replace() or etc?
Thanks
Edit:
I have this:
preg_replace('~\[.*!?\]~', '[replaced]', $parent);
But it return from "content[1][officeImage]" this "content[replaced]" :[
Try this:
preg_replace('~^.*\[\K[^]]+~m', 'replaced', $parent);
The m (multi-line) modifier is only necessary if $parent contains multiple lines needing to be replaced at once.
The big trick here is starting with ^.*\[\K. This says match everything starting with the beginning of the line up to a \[. Since this is a "greedy" repetition it will keep going until the last instance (. doesn't match newlines without the s modifier). The \K throws away everything matched so we only are replacing what's inside the brackets.
You can use this code:
$re = "/\\[([^]]*)\\][^]]*$/m";
$str = "content[1]\ncontent[1][officeImage]\ncontent[2][officeImage]\ncontent[3][something][officeImage]";
$subst = "[replacement]";
$result = preg_replace($re, $subst, $str);
See it live PHP or live Regex
Try this:
$string = 'content[3][something][officeImage]';
$replaced = 'somestring';
$result = preg_replace('/(.*\[)(.*?)]$/m','$1'.$replaced.']',$string);

How to replace an unknown string? (only pattern is known)

I want to replace a string which might appear within a URL.
The string has the following pattern:
%26TID%3D123456
I want to replace the 123456 part, to a specific value such as: 777777.
To be on the safe side though, I don't want to assume that the relevant part of the original string has necessarily 6 digits after the %3D part; I want to assume that the original string might contain a few more or few less characters (and I also can't tell the real value of each digit).
In addition, when I replace the string, since that string will usually appear in the middle of the URL, I need to replace it without modifying the rest of the URL. After that string, there would usually be another %26 string which I want to keep including whatever that is after it, but to be on the safe side, I don't want to assume that the original string is necessarily followed by %26.
What is the best practice to make such a replacement, that would stand up to all my above conditions?
The general rule is to specify the boundary (or an "anchor") (here, a starting one) and then match whatever you want with the more generic pattern.
Here, the "anchor" is the literal text TID%3D. The more generic pattern is one or more digits: \d+.
Since you need to replace the first occurrence, you need to pass 1 as the limit argument value in preg_replace.
So, combining all that:
$re = '~TID%3D\d+~';
$str = "%26TID%3D123456 %26PID%3D123456 %26TID%3D123456";
$subst = 'TID%3D7652';
echo $result = preg_replace($re, $subst, $str, 1);
// = > %26TID%3D7652 %26PID%3D123456 %26TID%3D123456
See IDEONE demo
If you do not want (or do not know) the "anchor" text, use a capturing mechanism (demo):
$re = '~(TID%\w{2})\d+~'; // (...) specify a capturing group referenced with ${1} later
$str = "%26TID%3D123456 %26PID%3D123456 %26TID%3D123456";
$subst = '${1}7652';
echo $result = preg_replace($re, $subst, $str, 1);
// = > %26TID%3D7652 %26PID%3D123456 %26TID%3D123456
You can also use a lookbehind approach, but it is less efficient:
$re = '~(?<=TID%3D)\d+~'; // (?<=TID%3D) makes sure digits are preceded with TID%3D substring
$str = "%26TID%3D123456 %26PID%3D123456 %26TID%3D123456";
$subst = '${1}7652';
echo $result = preg_replace($re, $subst, $str, 1);

Encode equal sign in query string with regex

I have a query string that may look like one of the following:
?key=aa=bb
?key=aa=bb=cc
?key=aa=bb&key2=cc
etc.
What I want to do is replace the equal sign in the value part only. So it should result in this:
?key=aa%3dbb
?key=aa%3dbb%3dcc
?key=aa%3dbb&key2=cc
I'm trying to do that with the following regex by using a look ahead. But it's not doing anything.
echo preg_replace("/=(?=[^&])=/", "%3d", 'http://www.example.com?key=aaa=bbb=ccc&key3=dddd');
Example code here
How can I make this work?
(\bkey\d*)=(*SKIP)(*F)|=
Try this.See demo.
https://regex101.com/r/hR7tH4/13
$re = "/(\\bkey\\d*)=(*SKIP)(*F)|=/m";
$str = "\n ?key=aa=bb\n ?key=aa=bb=cc\n ?key=aa=bb&key2=cc\n";
$subst = "%3d";
$result = preg_replace($re, $subst, $str);
You don't need regex, use the proper tools. parse_url() to get the query string (and whatever else you want), then parse_str() to get an array of the var/vals. Then http_build_query() will encode for you:
$query = parse_url('http://www.example.com?key=aaa=bbb=ccc&key3=dddd', PHP_URL_QUERY);
parse_str($query, $array);
$result = http_build_query($array);
Here is another version of a regex based on the same approach as vks':
[&?][^&=]+=(*SKIP)(*FAIL)|=
Regex explanation:
[&?] - Match & or ? literally
[^&=]+ - Match characters other than & and =
= - Match = (so, we matched a key)
(*SKIP)(*FAIL) - Verbs that fail the match at this point (we do not replace this = we found after key)
= - We match any other = and we'll remove it.
Here is IDEONE demo:
$re = "/[&?][^&=]+=(*SKIP)(*FAIL)|=/";
$str = "http://google.com?key=aa=bb\nhttp://google.com?key=aa=bb=cc\nhttp://google.com?key=aa=bb&key2=cc";
$result = preg_replace($re, "%3d", $str);
echo $result;
What about this?
preg_replace_callback("/=([^&$]+)/", "myReplace", "http://www.example.com?key=aaa=bbb=ccc&key3=dddd");
function myReplace($matches) {
return "=" . urlencode($matches[1]);
}
Just gonna add an addendum, explaining your specific attempt:
preg_replace("/=(?=[^&])=/",
↑ ↑
While the lookahead was a nice idea, it really just would match a single character. And in this case just would have asserted the very next character not to be &.
You could refashion it into:
preg_replace("/=([^&=]+)\K=/",
↑
Which I guess is what you tried. Note that this merely ignores every second =………= equal sign. So would only suit your simple example query strings, not more plentiful unescaped characters within.

RegEx for PHP preg_replace swapping matches and matching multiple instances

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);

Categories