fork download
  1. <?php
  2. function replaceFromPos($str, $reg, $repl, $pos = 0, $cnt = -1){
  3. return substr($str, 0, $pos).preg_replace($reg, $repl, substr($str, $pos, strlen($str)), $cnt);
  4. }
  5. $text = 'hello world! this world is great. world is big!';
  6. $pattern = '/(world)/i';
  7. $replacement = 'WORLD';
  8. // заменим одно слово, начиная с 10-ой позиции
  9. echo replaceFromPos($text, $pattern, $replacement, 10, 1) , PHP_EOL;
  10. // заменим всё, что после 10-ой позиции
  11. echo replaceFromPos($text, $pattern, $replacement, 10) , PHP_EOL;
  12. // заменим первые два вхождения с нулевой позиции
  13. echo replaceFromPos($text, $pattern, $replacement, 0, 2) , PHP_EOL;
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
hello world! this WORLD is great. world is big!
hello world! this WORLD is great. WORLD is big!
hello WORLD! this WORLD is great. world is big!