Basically what I\'m looking for is the PHP version of this thread: Find, replace, and increment at each occurence of string
I would like to replace the keyword follow
I prefer to use preg_replace_callback()
for this task . It is a more direct solution than making iterated single preg_replace()
calls which restart from the beginning of the string each time (checking text that has already been replaced).
^
means the start of a line because of the m
pattern modifier.\K
means restart the full string match. This effectively prevents the literal >
from being replaced and so only the literal string num
is replaced.static
counter declaration will only set $counter
to 0
on the first visit.Code: (Demo)
$text = <<<TEXT
>num, blah, blah, blah
ATCGACTGAATCGA
>num, blah, blah, blah
ATCGATCGATCGATCG
>num, blah, blah, blah
ATCGATCGATCGATCG
TEXT;
echo preg_replace_callback(
"~^>\Knum~m",
function () {
static $counter = 0;
return ++$counter;
},
$text
);
preg_replace(array_fill(0, 5, '/'.$findme.'/'), range(1, 5), $string, 1);
Example:
preg_replace(array_fill(0, 5, '/\?/'), range(1, 5), 'a b ? c ? d ? e f g ? h ?', 1);
Output
a b 1 c 2 d 3 e f g 4 h 5
$str = 'a hello a some a';
$i = 0;
while (strpos($str, 'a') !== false)
{
$str = preg_replace('/a/', $i++, $str, 1);
}
echo $str;
Here's my two cents
function str_replace_once($correct, $wrong, $haystack) {
$wrong_string = '/' . $wrong . '/';
return preg_replace($wrong_string, $correct, $haystack, 1);
}
The above function is used to replace the string occurence only once, but you are free to edit the function to perform every other possible operation.
If I understood your question properly...
<?php
//data resides in data.txt
$file = file('data.txt');
//new data will be pushed into here.
$new = array();
//fill up the array
foreach($file as $fK =>$fV) $new[] = (substr($fV, 0, 1)==">")? str_replace("num", $fK/2, $fV) : $fV;
//optionally print it out in the browser.
echo "<pre>";
print_r($new);
echo "</pre>";
//optionally write to file...
$output = fopen("output.txt", 'w');
foreach($new as $n) fwrite($output, $n);
fclose($output);