Search code examples
phpregexmodx

I need a php RegEx to find modx snippet call in html content


My regex is very-very weak, I need help writing [and hopefully understanding] a php regex to find a modx snippet call in the content field of a resource and extract one of the attributes of that call. The call will look like this:

[[ShowVideo? &path=`path/to/somevideo.mp4` &w=`960`&h=`540` &playlist=`true`]]

or possibly called un-cached

[[!ShowVideo? &path=`path/to/somevideo.mp4` &w=`960`&h=`540` &playlist=`true`]]

What I need to extract from that is the "path/to/somevideo.mp4" value from the path attribute.

How can I do that?

EDIT:

Thanks for your help guys - here is the completed snippet in case anyone is interested:

<?php

$rid = $modx->resource->get('id'); // this resource id

$children = $modx->getChildIds($rid,1); // get one level of child ids

$pattern = '~\[\[!?ShowVideo[^\]]*&?path=`([^`]*)`~'; // thanks Crayon Violent

$myPlaylist = ''; // output to placeholder

$listItems = ''; // list thumbs with link

$index = 1; // not actually used

$parents = $modx->getParentIds($rid); // get the parent id array

if(!$children){

    // try siblings 
    $children = $modx->getChildIds($parents[0]); // get children of immediate parent

    array_unshift($children, $parents[0]); // prepend immediate parent id

}else{

    // must be a parent folder?
    array_unshift($children, $rid); // prepend this id

}

$videos = $children; // just for readbility

foreach($videos as $video){

    $resource = $modx->getObject('modResource', $video); // get the first resource object

    if ($resource->get('id') == $rid){ // figure out if this is the current video [to add a css class]

        $current = ' current';

    }else{

        $current = '';

    }

    if($resource){ 

        $rescontent = $resource->getContent(); // get the unprocessed! content field

        if(preg_match($pattern, $rescontent, $matches)){ // thanks again crayon!

            $listItems .= $modx->getChunk('PlayListItems', array( // get the output chunk & populate it's placeholders

                'videopath' =>  $modx->makeUrl($resource->get('id')),
                'thumbnail' => $resource->getTVValue('PageThumbnail'),
                'current' => $current,

            ));

        }

    }

    $index++; // again ~ not used

}


$myPlaylist = $modx->getChunk('PlayListWrapper', array( // get and populate the wrapper chunk

    'ListItems' =>  $listItems,

));


return $myPlaylist; // output! 

Solution

  • preg_match('~&path=`([^`]*)`~',$string,$match);
    // $match[1] will have the value
    

    If it needs to be a little more explicit:

    preg_match('~\[\[!?ShowVideo[^\]]*&path=`([^`]*)`~',$string,$match);
    // $match[1] will have the value