Daviddd
Daviddd

Reputation: 791

php replace content between tags and keep them

I need to replace the content between those tags and keep the tags

$source="Original string <p>bal bla bla</p>**** <!--{date}-->REPLACE ME!!!<!--/{date}-->"
$replaceText = '2012-06-14';
$start = '<!--{date}-->';
$end = '<!--/{date}-->';

preg_replace('#('.preg_quote($start).')(.*)('.preg_quote($end).')#si', '$1'.$replaceText.'$3', $source);

The result is:

"Original string <p>bal bla bla</p>**** 012-06-14<!--/{date}-->"

Missing the start tag and the 2. Ideas?

Upvotes: 0

Views: 261

Answers (2)

Sena
Sena

Reputation: 914

Put a space between the var and the replaceText

Like that

preg_replace('#('.preg_quote($start).')(.*)('.preg_quote($end).')#si', '$1 '.$replaceText.' $3', $source);

Upvotes: 1

Michael Laffargue
Michael Laffargue

Reputation: 10294

That's because doing like this you obtain : '$12012-06-14$3' as the replacement. So I'm guessing it's taking $12 and not $1

You may want to test what's written in the doc ${1} instead of $1

Upvotes: 3

Related Questions