Replacing part of the string with regex - php

I have a string like this:
$string ='//upload.wikimedia.org/wikipedia/commons/thumb/6/6b/AkutanZero1.jpg/220px-AkutanZero1.jpg';
But I'm trying to replace a section of it with another:
$string ='//upload.wikimedia.org/wikipedia/commons/thumb/6/6b/AkutanZero1.jpg/123px-AkutanZero1.jpg';
I'm using trying to use preg_replace, and I know that the string will always end with /thumb/(a hex value)/(two hex values)/(stuff)/(one or more numbers)-px-(stuff)
Unfortunately I haven't been successful in getting the text replaced and don't know what I'm doing wrong.
It would be easy if I could assume /(one or more numbers)-px existing only once but it could also exist in the /(stuff) part too.
preg_replace('/\/thumb\/[0-9a-f]\/[0-9a-f]{2}\/.+\/([0-9]+)-px-.+$/i', '328', $string);
preg_replace('/(\/thumb\/[0-9a-f]\/[0-9a-f]{2}\/.+\/)([0-9]+)(-px-.+)$/i', $1.'328'.$3, $string);

Based on your single sample input, you don't need any capture groups to get the expected result. Just find the occurrence(s) of digits followed by px- and swap in your preferred value. If this isn't robust enough, please improve your question.
Code: (Demo)
$string='//upload.wikimedia.org/wikipedia/commons/thumb/6/6b/AkutanZero1.jpg/220px-AkutanZero1.jpg';
echo preg_replace('/\d+px-/','123px-',$string);
Output:
//upload.wikimedia.org/wikipedia/commons/thumb/6/6b/AkutanZero1.jpg/123px-AkutanZero1.jpg

Related

regular expression gone wrong

I want to find all strings looking like [!plugin=tesplugin arg=dfd arg=2!] and put them in array.
Important feature: the string could contain arg=uments or NOT(in some cases). and of course there could be any number of arg's. So the string could look like:
[!plugin=myname!] or [!plugin=whatever1 arg=22!] or even [!plugin=gal-one arg=1 arg=text arg=tx99!]. I need to put them all in $strarray items
Here is what i did...
$inp = "[!plugin=tesplugin arg=dfd!] sometxt [!plugin=second arg=1 arg=2!] 1sd";
preg_match_all('/\[!plugin=[a-z0-9 -_=]*!]/i', $inp, $str);
but $str[0][0] contains:
[!plugin=tesplugin arg=dfd!] sometxt [!plugin=second arg=1 arg=2!]
instead of putting each expression in a new array item..
I think my problem in regex.. but can't find one. Plz help...
The last ] needs to be escaped and the - in the character class needs to be at the start, end, or escaped. As is it is a range of ascii characters between a space and underscore.
\[!plugin=[a-z0-9 \-_=]*!\]
Regex101 Demo: https://regex101.com/r/zV4bO2/1

How to get a number from a html source page?

I'm trying to retrieve the followed by count on my instagram page. I can't seem to get the Regex right and would very much appreciate some help.
Here's what I'm looking for:
y":{"count":
That's the beginning of the string, and I want the 4 numbers after that.
$string = preg_replace("{y"\"count":([0-9]+)\}","",$code);
Someone suggested this ^ but I can't get the formatting right...
You haven't posted your strings so it is a guess to what the regex should be... so I'll answer on why your codes fail.
preg_replace('"followed_by":{"count":\d')
This is very far from the correct preg_replace usage. You need to give it the replacement string and the string to search on. See http://php.net/manual/en/function.preg-replace.php
Your second usage:
$string = preg_replace(/^y":{"count[0-9]/","",$code);
Is closer but preg_replace is global so this is searching your whole file (or it would if not for the anchor) and will replace the found value with nothing. What your really want (I think) is to use preg_match.
$string = preg_match('/y":\{"count(\d{4})/"', $code, $match);
$counted = $match[1];
This presumes your regex was kind of correct already.
Per your update:
Demo: https://regex101.com/r/aR2iU2/1
$code = 'y":{"count:1234';
$string = preg_match('/y":\{"count:(\d{4})/', $code, $match);
$counted = $match[1];
echo $counted;
PHP Demo: https://eval.in/489436
I removed the ^ which requires the regex starts at the start of your string, escaped the { and made the\d be 4 characters long. The () is a capture group and stores whatever is found inside of it, in this case the 4 numbers.
Also if this isn't just for learning you should be prepared for this to stop working at some point as the service provider may change the format. The API is a safer route to go.
This regexp should capture value you're looking for in the first group:
\{"count":([0-9]+)\}
Use it with preg_match_all function to easily capture what you want into array (you're using preg_replace which isn't for retrieving data but for... well replacing it).
Your regexp isn't working because you didn't escaped curly brackets. And also you didn't put count quantifier (plus sign in my example) so it would only capture first digit anyway.

Get specific string content inside big string

I have a big string like this:
[/az_column_text][/vc_column_inner][vc_column_inner width="3/4"]
[az_latest_posts post_layout="listed-layout" post_columns_count="2clm" post_categories="assemblea-soci-2015"]
[/vc_column_inner][/vc_row_inner][/vc_column]
What I need to extract:
assemblea-soci-2015
Of course this value can change, and also the big string can change too. I need a regex or something else to extract this value (it will be always from post_categories="my-value-to-extract") from this big string.
I think to take post_categories=" as the beginning of a possible substring and the next char " as the end of my portion, but no idea how to do this.
Is there an elegant way to do this also for future values with, of course, different length?
You can use this regex in PHP:
post_categories="\K[^"]+
RegEx Demo
You can use this regex:
(?<=post_categories=")[^"]+(?=")
?<= (lookbehind) looks for post_categories=" before the desired match, and (?=) (lookahead) looks for " after the desired match.
[^"] gets the match (which is assumed not to contain any ")
Demo
Example PHP code:
$text='[/az_column_text][/vc_column_inner][vc_column_inner width="3/4"]
[az_latest_posts post_layout="listed-layout" post_columns_count="2clm" post_categories="assemblea-soci-2015"]
[/vc_column_inner][/vc_row_inner][/vc_column]';
preg_match ("/(?<=post_categories=\")[^\"]+(?=\")/", $text,$matches);
echo $matches[0];
Output:
assemblea-soci-2015
This should extract what you want.
preg_match ("/post_categories=\"(.*)\"\[\]/", $text_you_want_to_use)

I want to split a string with preg_split and surround the results

I am trying to split a string with preg_split, take the results, surround them with custom data, and reinsert them into the original string.
For example:
$string="this is text [shortcode] this is also text [shortcode2] this is text";
Afterwards, I want string to equal:
$string="<span id='0'>this is text </span>[shortcode]<span id='1'> this is also text </span>[shortcode2]<span id='2'>this is text</span>";
I was successful at splitting the string into an array:
$array=preg_split(/\[[^\]]*\]/,$string);
I then tried a for next loop to replace the values - which worked OK, except if the array values had identical matches in the string.
Any help is appreciated - or another approach that might be better.
preg_split() is the wrong tool for this, I would suggest using a callback.
Below is an example to get you started in which you can modify it to your needs along the way.
$str = preg_replace_callback('~(?:\[[^]]*])?\K[^[\]]+~',
function($m) {
static $id = 0;
return "<span id='".$id++."'>$m[0]</span>";
}, $str);
eval.in demo

Simple regex replace regardless of middle text php

say I have this
searchpage-20/11111111111?node=15
how would I setup a regex to replace the entire string without worrying about the
11111111111
in the middle as long as the rest matches.
I tried
searchallmp3-20/(.+?)\?node=
You should post the code, to see how you are calling the regex and you need also to describe, what is not working.
I assume you are getting some error message because you are using / without escaping it in your regex and your delimiter is also the /
Two possibilities:
Escape the /
/searchallmp3-20\/(.+?)\?node=/
Use another delimiter
~searchallmp3-20/(.+?)\?node=~
See Delimiters on php.net
I still don't get the replace part of your question. If you want to remove the digits before the ?, you should capture the other parts of the string
~(searchallmp3-20/).+?(\?node=~)
and replace with
`$1$2`
this will result in
searchpage-20/?node=15
Is it this what you want?
How about
<?php
$search = 'searchpage-20/11111111111?node=15';
$reg = '#(searchpage-\d+/)\d+(\?node=\d+)#';
echo preg_replace($reg, '${1}blah${2}', $search);
OUTPUT
searchpage-20/blah?node=15
You should be able to use this:
/searchpage-(\d+)\/(\d+)\?node=(\d+)/
Example usage:
preg_replace('/searchpage-(\d+)\/(\d+)\?node=(\d+)/', '', 'searchpage-20/11111111111?node=15');

Categories