I need to convert an img like this:
<img src="https://techcrunch.com/wp-content/uploads/2015/04/codecode.jpg" style="height:404px; width:602px" />
to this:
<amp-img src="https://techcrunch.com/wp-content/uploads/2015/04/codecode.jpg" height="404" width="602"></amp-img>
Keeping in mind that this code will be in a portion of code with more html tags and, important, I can't use any library or anything..
I await answers, thanks in advance!
You can Achieve your goal with following code :
function html5toampImage($string) {
preg_match('/src="(.+?)"/', $string, $src);
$srcAttribute = $src[0];
preg_match('/style="(.+?)"/', $string, $styles);
$style = $styles[1];
$allData = explode(";",$style);
foreach($allData as $data) {
if($data) {
list($key,$value) = explode(":",$data);
if(trim($key)=="height") {
$heightAttribute = trim($key).'="'.trim(str_replace("px","",$value)).'"';
}
if(trim($key)=="width") {
$widthAttribute = trim($key).'="'.trim(str_replace("px","",$value)).'"';
}
}
}
$ampImageTag = '<amp-img '.$srcAttribute.' '.$heightAttribute.' '.$widthAttribute.' layout="responsive"></amp-img>';
return $ampImageTag;
}
$html5Tag = '<img alt="aa" src="https://techcrunch.com/wp-content/uploads/2015/04/codecode.jpg" style="height:404px; width:602px; color:red" />';
echo htmlentities(html5toampImage($html5Tag));
Here is working eval url
Related
I have a string that is for a blog, potentially it could have an unlimited number of images in this string, what I am trying to do is get all of the src="" and add a prefix to the url and use it as the hyperlink.
My string:
$test = 'Hello world
<img src="images/image1.jpg" />Line 2
<img src="images/image2.jpg" />Some text
<img src="images/image3.jpg" />';
I am able to prefix href. I am able to achieve this:
<img src="images/image1.jpg" />
<img src="images/image2.jpg" />
<img src="images/image3.jpg" />
This is my code so far:
$new = preg_replace('/(<img[^>]+src="([^\\"]+)"[^>]+\\/>)/','\\1',$test2);
echo $new;
I need to add foldername/as prefix in all the image src. What im trying to turn this into is the following:
<img src="foldername/images/image1.jpg" />
<img src="foldername/images/image2.jpg" />
<img src="foldername/images/image3.jpg" />
How can I do that?
To do this using DOMDocument rather than regex (a good reason is https://stackoverflow.com/a/1732454/1213708).
The code loads the HTML and then looks for all of the <img> tags. It first takes the value of src and adds the extra part to it. Then it creates a new <a> tag and also adds the (original) src value as the href attribute. It then replaces the <img> tag with the <a>, but adds the old value back into the <a>...
$dom = new DOMDocument();
$dom->loadHTML($test, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
foreach ( $dom->getElementsByTagName("img") as $image ) {
$src = $image->getAttribute("src");
$image->setAttribute("src", "foldername/".$src);
$anchor = $dom->createElement("a");
$anchor->setAttribute("href", $src);
$image->parentNode->replaceChild($anchor, $image);
$anchor->appendChild($image);
}
echo $dom->saveHTML();
Not that it matters now, but here is a parsing solution without regex. I prefer #NigelRen solution actually now that its posted. However, here is a way to build a list of image urls without regex that could be used for solving your issue and provide further exploration. I haven't tested the code but i'm pretty fair on it working.
<?php
$html = 'some html here';
$sentinel = '<img src="';
$quoteSentinel = '"';
$done = false;
$offset = 0;
$imageURLS = array();
while (!$done) {
$nextImageTagPos = strpos($html, $sentinel, $offset);
if ($nextImageTagPos !== false) {
//*** Parsing
// Find first quote
$quoteBegins = false;
for ($i = $nextImageTagPos; $i < $nextImageTagPos + 100; $i++) {
if (substr($html, $i, 1) == $quoteSentinel) {
$quoteBegins = $i;
break;
}
}
// Find ending quote
$quoteEnds = false;
if ($quoteBegins !== false) {
for ($i = $quoteBegins + 1; $i < $quoteBegins + 1000; $i++) {
if (substr($html, $i, 1) == $quoteSentinel) {
$quoteEnds = $i;
break;
}
}
if ($quoteEnds !== false) {
// Hooray! now we are getting somewhere
$imgUrlLength = ($quoteEnds - $quoteBegins) - 1;
$imgUrl = substr($html, $quoteBegins + 1, $imgUrlLength);
// ***Requirements
/*
I have a string that is for a blog, potentially it could have an unlimited number of images in this string, what i am trying to do is get all of the src="" and add a prefix to the url and use it as the hyperlink.
*/
// But for brevity lets skip requirements and build an array of URLs.
$imageURLS[] = $imgUrl;
$offset = $quoteEnds + 1;
}
}
// Extract url
}
else {
$done = true;
}
}
let's say we load the source code of this question and we want to find the url alongside "childUrl"
or goto this site source code and search "childUrl".
<?php
$sites_html = file_get_contents("https://stackoverflow.com/questions/46272862/how-to-find-urls-under-double-quote");
$html = new DOMDocument();
#$html->loadHTML($sites_html);
foreach() {
# now i want here to echo the link alongside "childUrl"
}
?>
Try this
<?php
function extract($url){
$sites_html = file_get_contents("$url");
$html = new DOMDocument();
$$html->loadHTML($sites_html);
foreach ($html->loadHTML($sites_html) as $row)
{
if($row=="wanted_url")
{
echo $row;
}
}
}
?>
you can use regex:
try this code
$matches = [[],[]];
preg_match_all('/\"wanted_url\": \"([^\"]*?)\"/', $sites_html, $matches);
foreach($matches[1] as $match) {
echo $match;
}
this will print all urls with wanted_url tag
I'm using Michel Fortin's PHP Markdown for Markdown converting but i want to show images as links instead of inline. Because anyone can insert a 5MB jpg from Imgur and slow down page.
How can i change images to link-to-image?
An example of an override would look something like the follwing:
class CustomMarkdown extends Markdown
{
function _doImages_reference_callback($matches) {
$whole_match = $matches[1];
$alt_text = $matches[2];
$link_id = strtolower($matches[3]);
if ($link_id == "") {
$link_id = strtolower($alt_text); # for shortcut links like ![this][].
}
$alt_text = $this->encodeAttribute($alt_text);
if (isset($this->urls[$link_id])) {
$url = $this->encodeAttribute($this->urls[$link_id]);
$result = "$alt_text";
} else {
# If there's no such link ID, leave intact:
$result = $whole_match;
}
return $result;
}
function _doImages_inline_callback($matches) {
$whole_match = $matches[1];
$alt_text = $matches[2];
$url = $matches[3] == '' ? $matches[4] : $matches[3];
$title =& $matches[7];
$alt_text = $this->encodeAttribute($alt_text);
$url = $this->encodeAttribute($url);
return "$alt_text";
}
}
Demo: http://codepad.viper-7.com/VVa2hP
You should have a look at Parsedown. It is a more recent and, I believe, easier to extend implementation of Markdown.
I am trying to replace image links, youtube video links and regular links separately with appropriate html tags and im having trouble targeting just the regular links:
Here's my code:
function($text)
{
$output = preg_replace('#(http://([^\s]*)\.(jpg|gif|png))#',
'<br/><img src="$1" alt="" width="300px" style = "clear:both;"/><br/>', $text);
$output = preg_replace('#(http://([^\s]*)youtube\.com/watch\?v=([^\s]*))#',
'<br/><iframe width="480px" height="385px" src="http://www.youtube.com/embed/$3"
frameborder="0" allowfullscreen style = "clear:both;"></iframe><br/>', $output);
$output = preg_replace('#(http://([^\s]*)\.(com))#',
'<br/>$1<br/>', $output);
return $output
}
This is instead replacing all links in the last step...how do i avoid this and replace only links (that arent youtubes or images) in the last step?
Thanks!
The urls your looking for need to be delimited by something such as spaces or new lines. Just add your delimiter to the regexes, so the the last regex is not too greedy! eg...
<?php
$text = "
http://www.youtube.com/watch?v=yQ4TPIfCK9A&feature=autoplay&list=FLBIwq18tUFrujiPd3HLPaGw&playnext=1\n
http://www.asdf.com/asdf.png\n
http://www.asdf.com\n
";
var_export($text);
var_export(replace($text));
function replace($text)
{
$output = preg_replace('#(http://([^\s]*)\.(jpg|gif|png))\n#',
'<br/><img src="$1" alt="" width="300px" style = "clear:both;"/><br/>', $text);
$output = preg_replace('#(http://([^\s]*)youtube\.com/watch\?v=([^\s]*))\n#',
'<br/><iframe width="480px" height="385px" src="http://www.youtube.com/embed/$3"
frameborder="0" allowfullscreen style = "clear:both;"></iframe><br/>', $output);
$output = preg_replace('#(http://([^\s]*)\.(com))\n#',
'<br/>$1<br/>', $output);
return $output;
}
You could use preg_replace_callback to match each link just once. So you don't have to worry about modifying a link twice:
$input = <<<EOM
http://www.example.com/fritzli.jpeg
https://www.youtube.com/watch?v=blabla+bla+"+bla
http://wwww.google.com/search?q=blabla
EOM;
echo replace($input);
function replace($text) {
$output = preg_replace_callback("#(https?://[^\s]+)#", function($umatch) {
$url = htmlspecialchars($umatch[1]);
if(preg_match("#\.(jpg|jpeg|gif|png|bmp)$#i", $url)) {
$result = "<br/><img src=\"$url\" alt=\"\" width=\"300px\" "
. " style = \"clear:both;\"/><br/>";
} elseif(preg_match("#youtube\.com/watch\?v=([^\s]+)#", $url, $match)) {
$result = "<br/><iframe width=\"480px\" height=\"385px\""
. " src=\"http://www.youtube.com/embed/{$match[1]}\""
. " frameborder=\"0\" allowfullscreen style = \"clear:both;\">"
. "</iframe><br/>";
} else {
$result = "<br/>$url<br/>";
}
return $result;
}, $text);
return $output;
}
Note: the code above works only with a PHP-version >= 5.3. If you use 5.3 or below you can just extract the inner function to a separate function and supply the function name as an argument to preg_replace_callback:
function replace_callback($umatch) {
$url = htmlspecialchars($umatch[1]);
if(preg_match("#\.(jpg|jpeg|gif|png|bmp)$#i", $url)) {
$result = "<br/><img src=\"$url\" alt=\"\" width=\"300px\" "
. " style = \"clear:both;\"/><br/>";
} elseif(preg_match("#youtube\.com/watch\?v=([^\s]+)#", $url, $match)) {
$result = "<br/><iframe width=\"480px\" height=\"385px\""
. " src=\"http://www.youtube.com/embed/{$match[1]}\""
. " frameborder=\"0\" allowfullscreen style = \"clear:both;\">"
. "</iframe><br/>";
} else {
$result = "<br/>$url<br/>";
}
return $result;
}
function replace($text) {
$output = preg_replace_callback("#(https?://[^\s]+)#",
"replace_callback", // the name of the inner function goes here
$text);
return $output;
}
My goal is to embed Tumblr posts into a website using their provided XML. The problem is that Tumblr saves 6 different sizes of each image you post. My code below will get the first image, but it happens to be too large. How can I select one of the smaller-sized photos out of the XML if all the photos have the same tag of <photo-url>?
→ This is the XML from my Tumblr that I'm using: Tumblr XML.
→ This is my PHP code so far:
<?php
$request_url = "http://kthornbloom.tumblr.com/api/read?type=photo";
$xml = simplexml_load_file($request_url);
$title = $xml->posts->post->{'photo-caption'};
$photo = $xml->posts->post->{'photo-url'};
echo '<h1>'.$title.'</h1>';
echo '<img src="'.$photo.'"/>"';
echo "…";
echo "</br><a target=frame2 href='".$link."'>Read More</a>";
?>
The function getPhoto takes an array of $photos and a $desiredWidth. It returns the photo whose max-width is (1) closest to and (2) less than or equal to $desiredWidth. You can adapt the function to fit your needs. The important things to note are:
$xml->posts->post->{'photo-url'} is an array.
$photo['max-width'] accesses the max-width attribute on the <photo> tag.
I used echo '<pre>'; print_r($xml->posts->post); echo '</pre>'; to find out $xml->posts->post->{'photo-url'} was an array.
I found the syntax for accessing attributes (e.g., $photo['max-width']) at the documentation for SimpleXMLElement.
function getPhoto($photos, $desiredWidth) {
$currentPhoto = NULL;
$currentDelta = PHP_INT_MAX;
foreach ($photos as $photo) {
$delta = abs($desiredWidth - $photo['max-width']);
if ($photo['max-width'] <= $desiredWidth && $delta < $currentDelta) {
$currentPhoto = $photo;
$currentDelta = $delta;
}
}
return $currentPhoto;
}
$request_url = "http://kthornbloom.tumblr.com/api/read?type=photo";
$xml = simplexml_load_file($request_url);
foreach ($xml->posts->post as $post) {
echo '<h1>'.$post->{'photo-caption'}.'</h1>';
echo '<img src="'.getPhoto($post->{'photo-url'}, 450).'"/>"';
echo "...";
echo "</br><a target=frame2 href='".$post['url']."'>Read More</a>";
}
To get the photo with max-width="100":
$xml = simplexml_load_file('tumblr.xml');
echo '<h1>'.$xml->posts->post->{'photo-caption'}.'</h1>';
foreach($xml->posts->post->{'photo-url'} as $url) {
if ($url->attributes() == '100')
echo '<img src="'.$url.'" />';
}
Maybe this:
$doc = simplexml_load_file(
'http://kthornbloom.tumblr.com/api/read?type=photo'
);
foreach ($doc->posts->post as $post) {
foreach ($post->{'photo-url'} as $photo_url) {
echo $photo_url;
echo "\n";
}
}