Home » , , , , » Mengambil URL Gambar Pertama dari Posting

Mengambil URL Gambar Pertama dari Posting

Versi PHP

function get_first_image_url($data, $default_url = null) {

// Matched with `![alt text](IMAGE URL)` from Markdown file
if(preg_match_all('/\!\[.*?\]\((.*?)\)/', $data, $matches)) {
return $matches[1][0];
}

// Matched with...
// 1. `<img src="IMAGE URL">`
// 2. `<img foo="bar" src="IMAGE URL">`
// 3. `<img src="IMAGE URL" foo="bar">`
// 4. `<img src="IMAGE URL"/>`
// 5. `<img foo="bar" src="IMAGE URL"/>`
// 6. `<img src="IMAGE URL" foo="bar"/>`
// 7. `<img src="IMAGE URL" />`
// 8. `<img foo="bar" src="IMAGE URL" />`
// 9. `<img src="IMAGE URL" foo="bar" />`
// ... and the uppercased version of them, and the single-quoted version of them
if(preg_match_all('/<img (.*?)?src=(\'|\")(.*?)(\'|\")(.*?)? ?\/?>/i', $data, $matches)) {
return $matches[3][0];
}

return $default_url; // Default image URL if nothing matched
}

Penggunaan

<img src="<?php echo get_first_image_url($page['content'], 'img/no-image.png'); ?>">

$page['content'] cuma contoh. Anda harus mengambilnya dari konten posting Anda sesuai dengan API pada CMS yang Anda pakai.

Versi JavaScript

function getFirstImageURL(data, noImage) {

// Matched with `![alt text](IMAGE URL)` from Markdown file
var matches = /\!\[.*?\]\((.*?)\)/.exec(data);
return matches ? matches[1] : noImage;

// Matched with...
// 1. `<img src="IMAGE URL">`
// 2. `<img foo="bar" src="IMAGE URL">`
// 3. `<img src="IMAGE URL" foo="bar">`
// 4. `<img src="IMAGE URL"/>`
// 5. `<img foo="bar" src="IMAGE URL"/>`
// 6. `<img src="IMAGE URL" foo="bar"/>`
// 7. `<img src="IMAGE URL" />`
// 8. `<img foo="bar" src="IMAGE URL" />`
// 9. `<img src="IMAGE URL" foo="bar" />`
// ... and the uppercased version of them, and the single-quoted version of them
matches = /<img (.*?)?src=(\'|\")(.*?)(\'|\")(.*?)? ?\/?>/i.exec(data);
return matches ? matches[3] : noImage;

}

Penggunaan

var img = '<img src="' + getFirstImageURL(sourceText, 'img/no-image.png') + '">';
document.write(img);

sourceText cuma contoh. Anda harus mengambilnya dari konten posting Anda, misalnya dengan cara ini:

var sourceText = document.querySelector('.post-body').innerHTML;
Jika Anda menyukai Artikel di blog ini, Silahkan klik disini untuk berlangganan gratis via email, dengan begitu Anda akan mendapat kiriman artikel setiap ada artikel yang terbit di Creating Website

0 comments:

Post a Comment

 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. Homtimpa - All Rights Reserved
Template Modify by Creating Website
Proudly powered by Blogger