tags:

views:

53

answers:

2

I have a string

$str = 'abcde-da__123123213.xef';
$str2 = 'asdfasd__2342352353.gff';
$str3 = 'twethe__3242323423.pig';

I want to replace anything following __ (2 underscores) and before the . (dot) with a new string (number). For example, the above $str changes to 'abcde-da__23235239.xef'.

One of the ways is to

$temp = explode('.', $str); 
$temp2 = explode('__', $temp[0]);

and

$new_str = $temp2[0].'__'.time().'.'.$temp[1];

But I was thinking if I could use preg_replace instead but I aint very good at regexs

i tried preg_replace('/__(.*)/', time(), 'abcde-da__123123213.xef');

can you please help writing this regex, or any other simpler way?

Thanks

+4  A: 
preg_replace('/(?<=__)([^.]+)(?=\.)/e','dosomething($1)',$str)

(?<=__) - LookBehind expression to match __
([^.]+) - Actual Match Part - match any characters except dot .
(?=\.)  - LookAhead expression to match .

e in /e allows to use php codes in replace part, dosomething() could be any functions like, time(),strtoupper(),$1 would be match string between __ and .

For more information about regexes, please take a look at regular-expressions.info

S.Mark
How about an explanation of what that does. The guy doesn't understand regex, so that would be helpful for him.
Richard June
Excellent .. it works and I can get the required string .. but the regex part just goes over head :D ..
+1  A: 

This regex is simpler: /.*?__(.*?)\..*/

".*" = absolutely anything. The '?' that follows means to not be greedy, which results in .*? matching everything up to __

"__" doesn't have any significance in regex, so it's matched literally

"(.*?)" again means match everything but don't be greedy. This will match the numbers

"\." we want to match the period character, but since it's a significant character in regex, we need to escape it so the regex engine knows we mean the actual character and not "anything"

".*" match anything. We can be greedy here because we're past the part we care about

So...

".*?__" matches everything before the number, and "\..*" matches everything after

Pickle