Chris Edwards
Chris Edwards

Reputation: 484

PHP Replace Between Tags with Regex

I am having a heck of a time replacing the data between two tags. I can't figure out the regex that will match this pattern. My tags are simply <!-- Model # Start --> and <!-- Model # End -->

Code:

        $products[''.$row[0].''][2] = preg_replace("/(<!-- Model # Start -->).*(<!-- Model # End -->)/i", "$1$2", $products[''.$row[0].''][2]);
        echo $products[''.$row[0].''][2] . "\n";

Data: $products[''.$row[0].''][2]

Economical. 7 mils thick, tough & stretchy. Each roll cellophane wrapped. UL listed.

<!-- Model # Start -->
<p style='text-align: right;'>16736</p>
<!-- Model # End -->

Upvotes: 0

Views: 1557

Answers (2)

morja
morja

Reputation: 8550

Try:

/(.*<!-- Model # Start -->).*(<!-- Model # End -->.*)/im

Note the m flag for multiline matches.

In case you have multiple occurances of the tags, you could use a reluctant quantifier to get the first match, or use lookaround.

http://rubular.com/ helps for testing.

Upvotes: 1

alex
alex

Reputation: 490123

I'd match it like so...

$match = 'Model\s#\s';

preg_replace('/<!--\s?' . $match . 'Start\s?(.*?)\s?' . $match . 'End\s?-->/i', '<span>$1</span>', $row);

Upvotes: 0

Related Questions