Page 1 of 1

help to build a regex to replace

Posted: Fri Jul 11, 2014 4:36 am
by CarlosMS
hi people

I'm new with regex in php and need help to build a regex

from a string like
xx_yy_zz_ww.php
I should get a string like
xx_yy_hh_ww.php
the components of the string are separated by underscores

hh xx yy zz are numbers and they have at least one digit, while ww is a text, a file name

so I should replace zz with hh, zz is the number in 3th position from left

thanks for helping me

Re: help to build a regex to replace

Posted: Fri Jul 11, 2014 5:38 am
by CarlosMS
I realized that I can simply explode and implode the string with '_' separator

Re: help to build a regex to replace

Posted: Sun Sep 28, 2014 2:19 am
by phpdeveloper1
CarlosMS wrote:...............................
so I should replace zz with hh, zz is the number in 3th position from left

.....................
One way could be

Code: Select all

$s = "12_1_22_ww.php";
$g = preg_replace('/([0-9]+_[0-9]+_)([0-9]+)(_[0-9a-z\.]+)$/i', '${1}33${3}' , $s);
print $g;