14 May 2022

Collection of all variants of str_replace function like functionality. Examples providing all kinds of solutions for your needs. From simple string replacement to regular expressions.

Source code viewer
  1. // Regular, replaces all occurrences.
  2. // str_replace(array|string $find_string, array|string $replace_with, string|array $subject, int &$count = null): string|array
  3. $string = str_replace('and', '&', 'search and replace');
  4. print $string; // Output: search & replace
  5.  
  6. // Input is array, replaces all occurrences.
  7. $char_list = array('!', '@');
  8. $string = str_replace($char_list, '', 'res@!ult');
  9. print $string; // Output: result
  10.  
  11. // Input and replacement are arrays, replaces with corresponding values.
  12. $subject = 'ABABABAB';
  13. $search = array('B', 'A');
  14. $replace = array('A', 'B');
  15. $string = str_replace($search, $replace, $subject);
  16. print $string; // Output: BBBBBBBB
  17. // The values are replaced in a loop. So it won't be BABABABA, as you might expect intuitively.
  18.  
  19. // Count the replacements.
  20. $count = 0;
  21. $str = str_replace('A', '', 'ABC', $count);
  22. print $count; // Output: 1
  23.  
  24. // ireplace means you can use the function in case-insensitive mode.
  25. $string = str_ireplace('AND', '&', 'search and replace');
  26. print $string; // Output: search & replace
  27.  
  28. // Using regular expression. Parentheses are used to determinate sub-patterns. Subpattern results are put to variables such as $1, $2, etc.
  29. // preg_replace(string|array $pattern, string|array $replacement, string|array $subject, int $limit = -1, int &$count = null): string|array|null
  30. echo preg_replace('/<picture(.*?)href=/', '<img$1src=', $subject);
Programming Language: PHP