John Davidson

php - Capture Group Not Captured in Preg_replace Replacement

0 comments
Message:


I have the following code:


$f = 'IMG_1474.PNG';
preg_replace('/(.*)([.][^.]+$)/', '$1' . time() . '$2', $f)

which should split the IMG_1474 and .PNG and add the epoch in between. The first capture group appears to be empty though.


If preg_match is used I can see the first capture group is not empty (so regex performs the same in PHP as on regex101).


preg_match('/(.*)([.][^.]+$)/', $f, $match);
print_r($match);

Functional demo: https://3v4l.org/VgDWJ (the 604147502 is the time() result)


My presumption is that something is happening with the concatenation on the replace bit.



My Answer:
To capture the first group in the replacement string in `preg_replace`, you can use `${1}` instead of `$1`. This will ensure that the captured group is properly replaced in the output. Here's the updated code:

php
$f = 'IMG_1474.PNG';
echo preg_replace('/(.*)([.][^.]+$)/', '${1}' . time() . '${2}', $f);


This will output something like `IMG_14741604147502.PNG`, where `1604147502` is the epoch time inserted between `IMG_1474` and `.PNG`.

Rate this post

3 of 5 based on 3823 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us