Howard Rhodes
Howard Rhodes

Reputation: 37

Replace matching word with a digit/number in a string in PHP

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

Upvotes: 0

Views: 118

Answers (2)

hwnd
hwnd

Reputation: 70732

You should be using preg_replace_callback() for this:

$str = preg_replace_callback('~\d\K\h*(?:too|for)|(?:too|for)\h*(?=\d)~i', 
     function($m) {
        return strtr(strtolower(trim($m[0])), array('too'=>2,'for'=>4));
     }, $str);

Upvotes: 1

Passerby
Passerby

Reputation: 10070

This may be a little too long, but you get the idea:

http://3v4l.org/JfXBN

<?php
$str="Please wait for sometime too, the area code is for 18 and phone number is too 5897 for";
$str=preg_replace('#(\d)\s*for#','${1}4',$str);
$str=preg_replace('#(\d)\s*too#','${1}2',$str);
$str=preg_replace('#for\s*(\d)#','4${1}',$str);
$str=preg_replace('#too\s*(\d)#','2${1}',$str);
echo $str;

Outputs:

Please wait for sometime too, the area code is 418 and phone number is 258974

Warning:

If your string looks like this: 8 too for,
this code snippet may or may not fail depending on whether you expect 824 or 82 for, since it does not do recursive replace (the current sequence returns 82 for).

Upvotes: 2

Related Questions