I have a string, for example
"The antelope is hungry today";
I want to search for "hungry" and replace whatever 3 characters are before it with "xxx" So the end result in this case would be
"The antelope xxxhungry today"
I thought maybe the substr_replace function might work, or maybe combining that with strlen, but I'm not getting it.
$str = "The antelope is hungry today"; // str to search $needle = "hungry"; // str to search for $start_index = strpos($str, $needle); // returns beginning index of 'hungry' (16 in this case) $result = substr_replace($str, "xxx", ($start_index - 3), 3); echo $result; // prints : The antelope xxxhungry today
See this phpfiddle for my working example.