Mostafa Mostafa - 3 months ago 6
PHP Question

Doing a modification in all numbers in text string

I have a lot of text strings, like that

'from 12.34 to 56.78'

OR

'12.34 to 56.78'

OR

'12.34'

I want to modify these number in all these strings

<?php
$array = explode(' ',$string);
foreach ($array as $value) {
if(is_numeric($value))
$newarray[] = round($value); // or other functions
else
$newarray[] = $value;
}
$newstring = implode(' ',$newarray);


Is this a best way for doing any modifications?

Jan Jan
Answer

As from your comments, you might have a look at preg_replace_callback().
Consider the following code which rounds all your numbers pretty easily:

<?php

$strings = array('from 12.34 to 56.78', '12.34 to 56.78', '12.34');
$values = array();

$regex = '~\b\d[\d.]+\b~';
foreach ($strings as $string) {
    $string = preg_replace_callback($regex,
        function($match) {
            // or anything else
            return round($match[0]);
        },
        $string);
    $values[] = $string;
}

print_r($values);
# [0] => from 12 to 57
# [1] => 12 to 57
# [2] => 12

?>
Comments