help to build a regex to replace

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
CarlosMS
Forum Newbie
Posts: 2
Joined: Fri Jul 11, 2014 4:26 am

help to build a regex to replace

Post 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
CarlosMS
Forum Newbie
Posts: 2
Joined: Fri Jul 11, 2014 4:26 am

Re: help to build a regex to replace

Post by CarlosMS »

I realized that I can simply explode and implode the string with '_' separator
phpdeveloper1
Forum Newbie
Posts: 19
Joined: Tue Aug 12, 2014 6:13 am
Location: Chennai, India

Re: help to build a regex to replace

Post 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;
Chris, Php Developer and Programmer,
https://www.phpfreelanceprogrammer.com/
Post Reply