user2188130
user2188130

Reputation: 3

preg_replace for replacing number value in string

Launguage used PHP TimeString = 1500-1550

I want to use preg_replace to change the 1550 half of the string to 1530. I tried to use a pattern of (/d|/d/d)50 Where I am getting stuck is I don't know how to use the replacement feature to change any /d50 or /d/d50 to have a 30 suffix. I don't want to sue str replace in php as it will change the first time 1500 to 130 since the 50 matches. Any ideas?

Upvotes: 0

Views: 1325

Answers (3)

Mustapha
Mustapha

Reputation: 101

Here..

<?php
    $numbers = array (1500, 1550, 140, 150, 15000);
    foreach ($numbers as $number) {
        echo preg_replace('/(\d|\d\d)50\b/', '${1}30', $number);
        echo "\n";
    }
?>

Will return:

1500
1530
140
130
15000

Upvotes: 2

Svish
Svish

Reputation: 157991

To match digits you need to use \d. Not /d.

Upvotes: 1

rid
rid

Reputation: 63442

preg_replace('/(\d\d)50/', '${1}30', $string)

Upvotes: 0

Related Questions