<pre>
<?php
$arr = [
'001.Porus.2017.S01E01.The.Epic.Story.Of.A.Warrior.720.x264.mp4',
'002.Porus.2017.S01E01.Welcome.With.A.Fight.720.x264.mp4',
'003.Porus.2017.S01E01.Anusuya.Stays.in.Poravs.720.x264.mp4',
'004.Porus.2017.S01E01.Olympia.Prays.For.A.Child.720.x264.mp4'
];
$your_next_number = "some_number";
$modified_values = [];
foreach($arr as $each_value){
$modified_values[] = str_replace("S01E01","S01".$your_next_number,$each_value);
//$your_next_number = something;some change that you want to make to your next iterable number.
}
print_r($modified_values);
OUTPUT
Array
(
[0] => 001.Porus.2017.S01some_number.The.Epic.Story.Of.A.Warrior.720.x264.mp4
[1] => 002.Porus.2017.S01some_number.Welcome.With.A.Fight.720.x264.mp4
[2] => 003.Porus.2017.S01some_number.Anusuya.Stays.in.Poravs.720.x264.mp4
[3] => 004.Porus.2017.S01some_number.Olympia.Prays.For.A.Child.720.x264.mp4
)
UPDATE
You can replace the code inside the foreach with the code below.
Credits to @ArtisticPhoenix for providing this improvisation and explanation of it.
foreach($arr as $each_value){
$modified_values[] = preg_replace('/^(\d+)([^S]+)(S01E)(\d+)/', '\1\2\3\1', $each_value);
}
^(\d+)
=> This is group 1
. Capture (^ at the start) and digits (\d) one or
more (+).
([^S])+
=> This is group 2
. Capture anything but a capital S ([^S]) one or more (+).
(S01E)
=> This is group 3
. Capture S01E as it is.
(\d+)
- This is group 4
. Capture digits present after (S01E).
Note that group numbers have 1
based indexing since group 0
is the entire regex.
Replacement Part:
- The replacement is
\1\2\3\1
.
- The syntax
\
followed by an integer
(represents a group number) is known as backreferencing. This says that match the same set of characters you got
from matching that group.
- So, put the 1st,2nd and 3rd capture back where
they came from, then the 4th capture is replaced with the 1st, this is the
initial digits replacing the last digits in the match.
So, let's take 001.Porus.2017.S01E01.The.Epic.Story.Of.A.Warrior.720.x264.mp4
as an example-
(\d+)([^S]+)(S01E)(\d+)
matches this way => (001)(.Porus.2017.)(S01E)(01)
Hence, replacement makes it as (001)(.Porus.2017.)(S01E)(001)
(notice the last change because of \1
at the end in the replacement \1\2\3\1
. Rest of the string remains the same anyway.