I want to replace some words in a string with a digit/number only if that word is followed or preceded by a digit [whitespace(s) allowed in between]. For example, here is an example string in which I wish to replace too with 2 and for with 4. I have tried with str_replace, but doesn't serve the full purpose as it replaces all for and too in the string
$str = 'Please wait for sometime too, the area code is for 18 and phone number is too 5897 for';
$str = str_ireplace(' for ', '4', $str);
$str = str_ireplace(' too ', '2', $str);
echo $str;
but it isn't giving me the desired output which should be Please wait for sometime too, the area code is 418 and phone number is 258974