Replace substrings with an incremented counter value

后端 未结 5 1881
耶瑟儿~
耶瑟儿~ 2021-01-17 08:25

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

相关标签:
5条回答
  • 2021-01-17 09:05

    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.
    • the static counter declaration will only set $counter to 0 on the first visit.
    • the custom function does not need to receive the matched substring because the entire full string match is to be replaced.

    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
         );
    
    0 讨论(0)
  • 2021-01-17 09:14
    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
    
    0 讨论(0)
  • 2021-01-17 09:23
    $str = 'a hello a some a';
    $i = 0;
    
    while (strpos($str, 'a') !== false)
    {
        $str = preg_replace('/a/', $i++, $str, 1);
    }
    
    echo $str;
    
    0 讨论(0)
  • 2021-01-17 09:26

    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.

    0 讨论(0)
  • 2021-01-17 09:29

    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);
    
    0 讨论(0)
提交回复
热议问题