CheeseFlavored CheeseFlavored - 7 months ago 75
PHP Question

PHP Replace part of a string before the substring I search for

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.
Thank you.


You can use strpos() and substr_replace() in combination to get your desired behavior:

$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.