0
$pedit =<<<head
<div class="item"><div var="i_name_10">white gold</div> <div 
var="i_price_10">$5.99</div></div> 
head;

echo preg_replace("/(<[^>]+var=\"i_price_10\"[^>]*>)(.*?)(<\/[^>]+? 
>\s*)/","$1".'100'."$3",$pedit);

Result:

<div class="item"><div var="i_name_10">white gold</div> 00</div>

Expected

    <div class="item"><div var="i_name_10">white gold</div><div 
    var="i_name_10">100</div> </div>

That seem to happen with any number even when i try casting it as string.

kim li
  • 21
  • 3
  • Related: [Replace html content without replacing the tags or attributes - PHP](https://stackoverflow.com/q/53973366/2943403) and [Replace a string with another in HTML but no in HTML tags and attributes PHP](https://stackoverflow.com/q/10950741/2943403) – mickmackusa Apr 15 '23 at 08:39

1 Answers1

1

Despite the fact that you isolated your backreference as a separate string and concatenate with '100', the parser still reads it as one string. This means the replacement string in your question is equivilent to:

'$11' . '00' . '$3'

You can isolate the backreference next to a number using braces and skip the concatenation:

'${1}100$3'

All that said, there are other problems with your regex and regex is notoriously bad at parsing html. If your goal is to modify the text content of an html string you might consider using DOMDocument:

// load your html string into DOMDocument
$dom = new DOMDocument();
$dom->loadHTML($pedit, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
// xpath makes it easier to query for attributes like "var" in this case
$xpath = new DOMXPath($dom);
$els = $xpath->query('//div[@var="i_price_10"]');
foreach ($els as $el) {
    // you can do whatever you'd like to the text node here
    $el->textContent = '100';
}
echo $dom->saveHTML();