Mecha CMS

Code snippet collection for developers.

Images Field

Extract images URL from page content.

Extract images URL from page content and put them in $page->images as array:

Hook::set('page.images', function($images, $lot) {
    $s = Page::open($lot['path'])->get('content');
    if (!$s || stripos($s, '<img ') === false) {
        return (array) $images;
    }
    if (preg_match_all('#<img(?:\s[^<>]*?)?\s+src=(["\'])(.+?)\1#i', $s, $m)) {
        return $m[2];
    }
    return (array) $images;
});

Extract the first image URL from page content and put them in $page->image as string:

Hook::set('page.image', function($image, $lot) {
    $s = Page::open($lot['path'])->get('content');
    if (!$s || stripos($s, '<img ') === false) {
        return $image;
    }
    if (preg_match('#<img(?:\s[^<>]*?)?\s+src=(["\'])(.+?)\1#i', $s, $m)) {
        return $m[2];
    }
    return $image;
});

Info: The plugin version of this snippet is now available as image plugin.