-1

I want to manipulate content

$description = 'Title <div data-type="page" data-id="1">Abcdef</div><div data-type="page" data-id="2">Fghij</div>';

I use preg_match to take value of data-type & data-id

if (preg_match('/<div data-type="(.*?)" data-id="(.*?)">(.*?)<\/div>/s', $description) ) { ... }

Not so sure with this regex, i expected to get

array(0 => array('type' => 'page', 'id' => 1), 1 => array('type' => 'page', 'id' => 1))

And using function get_page_content($id) to return real content by id, finally my content look like this : Title this is page id 1 this is page id 2

Solved: (Temporary)

$regex = '/<div data-type="(.*?)" data-id="(.*?)">(.*?)<\/div>/';
$description = 'Title <div data-type="page" data-id="1">Abcdef</div><div data-type="page" data-id="2">Fghij</div>';

echo preg_replace_callback(
        $regex,
        function($match) {
            if (isset($match[1]) && isset($match[2])) {
                if ($match[1] == 'page') {
                    return '<div class="page-embed">'. get_page_content($match[2]) .'</div>';
                }
            }

            return false;
        },
        $description);
Anatasya
  • 1
  • 1
  • I think you need to check the [*Extract HTML attributes in PHP with regex*](http://stackoverflow.com/questions/22578718/extract-html-attributes-in-php-with-regex) post. Regex is not the best tool to work with HTML. Consider [this post](http://stackoverflow.com/a/3577654/3832970) as well. – Wiktor Stribiżew Dec 07 '15 at 11:04

1 Answers1

1

First of all, regex is not the best option for DOM related texts. However, for your particular problem, this should do.

$string = 'Title <div data-type="page" data-id="1">Abcdef</div><div data-type="page" data-id="2">Fghij</div>';
$pattern = '<div data-type="(?P<type>[^"]+?)" data-id="(?P<id>[^"]+?)">(?P<div_contents>[^<]+?)<\/div>';

preg_match('/'.$pattern.'/', $string, $matches);

The $matches array will contains following:

Array ( [0] =>Abcdef [type] => page [1] => page [id] => 1 [2] => 1 [div_contents] => Abcdef [3] => Abcdef )

Therefore, to get type, id and contents between div you can simply do,

$type = $matches['type'];
$id = $matches['id'];
$contents = $matches['div_contents'];
DrGeneral
  • 1,844
  • 1
  • 16
  • 22