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.

1

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.