fork download
  1. <?php
  2.  
  3. $str = "men's black hat, white shirt and orange shirt!";
  4.  
  5. $words = preg_split('/\W*(\s+|$)\W*/', $str, -1, PREG_SPLIT_OFFSET_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6.  
  7. $targets = array('hat', 'shirt');
  8. $shield = 'men\'s';
  9. $bias = 0;
  10.  
  11. for ($i = 0; $i < count($words); ++$i) {
  12. list ($word, $offset) = $words[$i];
  13.  
  14. if (!in_array($word, $targets)) {
  15. continue;
  16. }
  17.  
  18. for ($j = max($i - 2, 0); $j < $i; ++$j) {
  19. if ($words[$j][0] === $shield) {
  20. continue 2;
  21. }
  22. }
  23.  
  24. $replacement = 'FOO';
  25. $str = substr_replace($str, $replacement, $offset + $bias, strlen($word));
  26. $bias += strlen($replacement) - strlen($word);
  27. }
  28.  
  29. echo $str;
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
men's black hat, white FOO and orange FOO!