str_ireplace
str_ireplace(array|string $search, array|string $replace, string|array $subject, int &$count = null): string|array
Case-insensitive replace: the case-insensitive twin of str_replace (ASCII-only folding since 8.2); array arguments map pairwise in order; &$count receives the replacement count.
C C23
/* No str_ireplace in libc: fold an ASCII copy, scan with strstr(3),
splice the replacement - counting hits along the way. */
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void) {
const char *s = "Cat catalog CAT";
const char *needle = "cat", *repl = "dog";
char lo[64] = {0}; /* zero-initialized folded copy */
size_t i;
for (i = 0; s[i]; ++i) lo[i] = (char)tolower((unsigned char)s[i]);
char out[128] = {0};
size_t pos = 0, j = 0;
int count = 0;
while (lo[pos]) {
char *hit = strstr(lo + pos, needle);
if (!hit) break;
size_t cut = (size_t)(hit - lo);
for (; pos < cut; ++pos) out[j++] = s[pos]; /* unmatched part */
for (const char *r = repl; *r; ++r) out[j++] = *r; /* replacement */
pos += strlen(needle);
++count;
}
for (; lo[pos]; ++pos) out[j++] = s[pos];
printf("%s\n%d replacement(s)\n", out, count);
return 0;
}
dog dogalog dog 3 replacement(s)
C++ C++26
// Hand-written fold-ASCII search-and-splice (no std::str_ireplace).
#include <cctype>
#include <iostream>
#include <string>
static std::string ascii_lower(std::string s) {
for (char& c : s) c = (char)std::tolower((unsigned char)c);
return s;
}
int main() {
std::string s = "Cat catalog CAT";
const std::string needle = "cat", repl = "dog";
std::string lo = ascii_lower(s);
std::string out;
size_t pos = 0;
int count = 0;
while (true) {
size_t hit = lo.find(needle, pos);
if (hit == std::string::npos) break;
out += s.substr(pos, hit - pos); // unmatched part (original case)
out += repl;
pos = hit + needle.size();
++count;
}
out += s.substr(pos);
std::cout << out << "\n" << count << " replacement(s)\n";
}
dog dogalog dog 3 replacement(s)
C# v11.0.100
// Regex.Replace with RegexOptions.IgnoreCase is the direct twin;
// a MatchEvaluator reproduces the array search/replace mapping.
using System.Text.RegularExpressions;
Console.WriteLine(Regex.Replace("Hello World, hello WORLD", "world", "PHP", RegexOptions.IgnoreCase));
Console.WriteLine(Regex.Replace("Cat catalog CAT", "cat", "dog", RegexOptions.IgnoreCase));
int count = 0;
var replaced = Regex.Replace("color BOOK", "o", _ => { count++; return "0"; }, RegexOptions.IgnoreCase);
Console.WriteLine($"{replaced} ({count} replacements)");
Console.WriteLine(Regex.Replace("apple pie", "a|e", m => m.Value == "a" ? "@" : "3", RegexOptions.IgnoreCase));
Hello PHP, hello PHP dog dogalog dog c0l0r B00K (4 replacements) @ppl3 pi3
Go v1.27.4
// regexp with the (?i) flag: the Go way to express case-insensitive replace.
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile("(?i)world")
fmt.Println(re.ReplaceAllString("Hello World, hello WORLD", "PHP"))
re2 := regexp.MustCompile("(?i)cat")
fmt.Println(re2.ReplaceAllString("Cat catalog CAT", "dog"))
count := 0
re3 := regexp.MustCompile("(?i)o")
out := re3.ReplaceAllStringFunc("color BOOK", func(string) string { count++; return "0" })
fmt.Printf("%s (%d replacements)\n", out, count)
re4 := regexp.MustCompile("a|e")
fmt.Println(re4.ReplaceAllStringFunc("apple pie", func(s string) string {
if s == "a" { return "@" }
return "3"
}))
}
Hello PHP, hello PHP dog dogalog dog c0l0r B00K (4 replacements) @ppl3 pi3
Java v27.0.1
// String.replaceAll with the (?i) embedded flag: the java twin of str_ireplace.
public class Main {
public static void main(String[] args) {
System.out.println("Hello World, hello WORLD".replaceAll("(?i)world", "PHP"));
System.out.println("Cat catalog CAT".replaceAll("(?i)cat", "dog"));
// Matcher.replaceAll(Function) is the counting/mapping form
var m = java.util.regex.Pattern.compile("(?i)o").matcher("color BOOK");
int[] count = {0};
var replaced = m.replaceAll(x -> { count[0]++; return "0"; });
System.out.println(replaced + " (" + count[0] + " replacements)");
var m2 = java.util.regex.Pattern.compile("a|e").matcher("apple pie");
System.out.println(m2.replaceAll(x -> x.group().equals("a") ? "@" : "3"));
}
}
Hello PHP, hello PHP dog dogalog dog c0l0r B00K (4 replacements) @ppl3 pi3
JavaScript v26.13.1
// replaceAll with the /gi flags: JavaScript's case-insensitive replace;
// a counter callback reproduces str_ireplace's $count argument.
let count = 0;
const replaced = "color BOOK".replaceAll(/o/gi, () => { count++; return "0"; });
console.log("Hello World, hello WORLD".replaceAll(/world/gi, "PHP"));
console.log("Cat catalog CAT".replaceAll(/cat/gi, "dog"));
console.log(`${replaced} (${count} replacements)`);
console.log("apple pie".replaceAll(/a|e/g, (m) => (m === "a" ? "@" : "3")));
Hello PHP, hello PHP dog dogalog dog c0l0r B00K (4 replacements) @ppl3 pi3
PHP v8.6.0
// str_ireplace - case-INSENSITIVE replace (ASCII folding since 8.2).
// Same shape as str_replace; $count receives the replacement count,
// and array search/replace arguments map pairwise in order.
echo str_ireplace("world", "PHP", "Hello World, hello WORLD"), "\n";
echo str_ireplace("cat", "dog", "Cat catalog CAT"), "\n";
$count = 0;
echo str_ireplace("o", "0", "color BOOK", $count), " ({$count} replacements)\n";
print_r(str_ireplace(["a", "e"], ["@", "3"], "apple pie"));
Hello PHP, hello PHP dog dogalog dog c0l0r B00K (4 replacements) @ppl3 pi3
Python v3.15.2
# re.sub with flags=re.IGNORECASE: the python twin of str_ireplace;
# a counter callback reproduces the $count argument.
import re
print(re.sub("world", "PHP", "Hello World, hello WORLD", flags=re.IGNORECASE))
print(re.sub("cat", "dog", "Cat catalog CAT", flags=re.IGNORECASE))
count = 0
def zero(_): # count replacements as they happen
global count
count += 1
return "0"
replaced = re.sub("o", zero, "color BOOK", flags=re.IGNORECASE)
print(f"{replaced} ({count} replacements)")
print(re.sub("a|e", lambda m: "@" if m.group(0) == "a" else "3", "apple pie"))
Hello PHP, hello PHP dog dogalog dog c0l0r B00K (4 replacements) @ppl3 pi3
Rust v1.99.1
// std has no case-insensitive replace: fold-ASCII scan + splice, counting
// hits (the regex crate would be the ecosystem answer; kept on std here).
fn main() {
let s = "Cat catalog CAT";
let (needle, repl) = ("cat", "dog");
let lo = s.to_ascii_lowercase();
let mut out = String::new();
let mut pos = 0usize;
let mut count = 0usize;
while let Some(rel) = lo[pos..].find(needle) {
let hit = pos + rel;
out.push_str(&s[pos..hit]); // unmatched part (original case)
out.push_str(repl);
pos = hit + needle.len();
count += 1;
}
out.push_str(&s[pos..]);
println!("{}\n{} replacement(s)", out, count);
}
dog dogalog dog 3 replacement(s)
TypeScript v26.13.1
// Same as JavaScript: replaceAll with /gi flags plus a counting callback.
let count: number = 0;
const replaced: string = "color BOOK".replaceAll(/o/gi, () => { count++; return "0"; });
console.log("Hello World, hello WORLD".replaceAll(/world/gi, "PHP"));
console.log("Cat catalog CAT".replaceAll(/cat/gi, "dog"));
console.log(`${replaced} (${count} replacements)`);
console.log("apple pie".replaceAll(/a|e/g, (m: string) => (m === "a" ? "@" : "3")));
Hello PHP, hello PHP dog dogalog dog c0l0r B00K (4 replacements) @ppl3 pi3
Language differences
C: no libc twin - hand-write the three-part "ASCII-folded copy + strstr scan + splice" (exactly this minimal implementation; the unmatched part keeps its original case). C++: the same hand-written shape (find + substr splicing). C#: Regex.Replace(s, pattern, repl, RegexOptions.IgnoreCase) - fixed-string replace rides the regex engine; a MatchEvaluator handles array mapping and counting. Go: regexp.MustCompile("(?i)") + ReplaceAllString (ReplaceAllStringFunc for counting). Java: String.replaceAll("(?i)...") (the inline flag avoids constructing a Pattern); Matcher.replaceAll(Function) is the mapping form. JavaScript/TypeScript: replaceAll(/cat/gi, ...); a callback closure counts. PHP: search/replace/subject all accept arrays - pairwise in order (mismatched lengths fall back to empty string, keyed by search); &$count receives the total; since 8.2 ASCII-only folding, locale-free; an array $subject returns an array (batch replace); known trap: in array mode a later search can re-hit earlier replacements (serial semantics) - use strtr (single pass) when that matters. Python: re.sub(flags=re.IGNORECASE); count via a replacement-function closure. Rust: none in std - hand-written fold scan; the ecosystem answer is the regex crate. Teaching anchor: two implementation philosophies for case-insensitive replace - a fixed-string engine (PHP str_ireplace hand-written scan) vs a regex-engine flag (the other languages’ (?i)/IGNORECASE); the count parameter is the only language-agnostic observable side channel.