Dezigo
Dezigo

Reputation: 3256

regex find -> found and replace


I have this code!

<div class="time\54>  
<div class="time\98">  
<div class="time\69">  
<div id="result">{INFO}</div>  

I need to take last

'<div class="time\69">'

Then take numbers in this last div after 'time',and sum it (6+9), then put result into {INFO} field.
Need use only preg_replace

Result:

<div class="time\54>  
<div class="time\98">  
<div class="time\69">  
<div id="result">15</div>  

How to take last child (element div)?
How to do a sum of numbers?
How to remember (use $1 , or %1) ?
Thx.

Upvotes: 1

Views: 185

Answers (3)

Oyeme
Oyeme

Reputation: 11235

$src = '<div class="edit\5451" style="width:100%; text-align:left">  
<div style="padding:0px 25px 0px 25px" align="left" class="edit\9874">  
<div class="edit\6924" style="padding:0px 0px 6px 0px">  
<div id="result">{RESULT}</div> ';

echo preg_replace('#(<div class="edit[\\\])([0-9]+)("[^<]+<div id="result">)([^<]+)(</div>)#mse','"$1$2$3".array_sum(str_split($2))."$5"', $src);

Upvotes: 1

Crozin
Crozin

Reputation: 44396

How to take last child (element div)?

Regexp is not a proper tool for dealing with HTML. Use DOMDocument::loadHTML() to create a DOM tree, then accessing last <div class="time\..."> should be easy.

How to do a sum of numbers?

$number = '69';
$digits = str_split($number); // Array (0 => 6, 1 => 9)
$sum    = array_sum($digits);   // 15

Upvotes: 0

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99919

Assuming you have to use preg_replace, the following would work:

$str = '<div class="time\54>
<div class="time\98">
<div class="time\12">  
<div class="time\69">
<div id="result">{INFO}</div>';

function replace_callback($matches) {
        return $matches[1] . array_sum(str_split($matches[2],"1"));
}

$result = preg_replace_callback('#((?:.*<div class="time\\\\\d+">)*.*<div class="time\\\\(\d+)">.*)\{INFO\}#s', 'replace_callback', $str);

If you can't even use preg_replace_callback, this is an alternative with only preg_replace:

$result = preg_replace('#((?:.*<div class="time\\\\\d+">)*.*<div class="time\\\\(\d+)">.*)\{INFO\}#se', '\'\1\' . array_sum(str_split(\'\2\',\'1\'))', $str);

Upvotes: 1

Related Questions