how can i get first img from html code by php - php

i want get first img from html code by php
i have this code
$text = '
<b>hello</b>
this is the first img
<img src="http://localhost/1.png" title="first img" />
other img
<img src="http://localhost/2.png" title="other" />
';
I want the first source image in a new variable
http://localhost/1.png
thanks

Use preg_match function
preg_match('/< *img[^>]*src *= *["\']?([^"\']*)/i', $text, $img);
echo $img[1]; // http://localhost/1.png

$text = '
<b>hello</b>
this is the first img
<img src="http://localhost/1.png" title="first img" />
other img
<img src="http://localhost/2.png" title="other" />
';
$pattern = '/src=\"(.*?)\"/g';
preg_match($pattern, $text, $matches);
print_r($matches);

$text = '
<b>hello</b>
this is the first img
<img src="http://localhost/1.png" title="first img" />
other img
<img src="http://localhost/2.png" title="other" />
';
preg_match('/<img.+src=[\'"](?P<src>.+)[\'"].*>/i', $text , $image);
echo $image['src'];

Related

Dynamically add img alt tags within HTML markup in PHP

I have HTML in which I echo onto a page using HTML. The HTML markup contains images, some of which don't have alt tags. There is no set format for the image markup - as it was exported from WordPress, which has messed around with the formatting.
I need to be able to parse the HTML, find the images without an alt tag, or an empty alt tag and populate that with text.
try this:
It try to find the img without the alt property or width empty alt="".
than replace the images with alt=" my_text "
$content = '
replace alt <img src="aaaa" alt="" />
replace alt <img src="bbbb" alt=" " />
replace alt <img src="cccc" />
do nothing <img src="dddd" alt="xxxxxxx" />
do nothing <img src="eeee" alt="yyyyy" />
error: <img src="ffff" alt="" alt=" " />
';
function replace_alt($html_content, $alt_text='')
{ $count = preg_match_all('/<img[^>]+>/i', $html_content, $images);
if($count>0)
{ $o = $html_content;
$t = 'alt="'.$alt_text.'" ';
foreach($images[0] as $img)
{ $is_alt = preg_match_all('/ alt="([^"]*)"/i', $img, $alt);
if($is_alt==0)
{ $new_img = str_replace('<img ', '<img '.$t , $img);
$o = str_replace($img, $new_img, $o);
}
elseif($is_alt==1)
{ $text = trim($alt[1][0]);
if(empty($text))
{ $new_img = str_replace(trim($alt[0][0]), $t, $img);
$o = str_replace($img, $new_img, $o);
}
}
}
}
return $o;
}
echo replace_alt($content, 'TEST');
$content should be your full HTML page....

preg-replace image width, height and style

My image looks like this:
<img alt="" width="146" height="109" src="http://url.to/src.jpg" style="float:left" />
but i can't figure out how to bring it with preg_replace or preg_replace_callback to this:
<img alt="" src="http://url.to/src.jpg" style="width:146;height:109;float:left">
This works with height and width but I can't get the style-element "float:left" added
$html='<img alt="" width="146" height="109" src="http://url.to/src.jpg" style="float:left" />';
$pattern = ('/<img[^>]*width="(\d+)"\s+height="(\d+)">/');
preg_match($pattern, $html, $matches);
$style = "<img style=\"width:".$matches[1]."px; height:".$matches[2]."px;\"";
$html = preg_replace($pattern, $style, $html);
result of this will be
<img alt="" style="width:146;height:109" src="http://url.to/src.jpg" style="float:left">
which didn't work because of the double style element
Try the following regular expression
<?php
$html='<img alt="" width="146" height="109" src="http://placehold.it/140x200" style="float:left" />';
$pattern = '/(<img.*)width="(\d+)" height="(\d+)"(.*style=")(.*)" \/(>)/';
$style = '$1$4width:$2px;height:$3px;$5';
$html = preg_replace($pattern, $style, $html);
echo $html; //view source of page to see the code change
?>
Note the use of brackets '(' ')' to create groups matched that can be later referenced using $1 $2 etc go to regex101.com and try out the regular expression.
Above code will result in following, except the last part, that shouldn't matter but you can modify it further.
<img alt="" src="http://placehold.it/140x200" style="width:146;height:109;float:left" />

Counting img tags line by line

I'm trying to count all <img> tags inside a string line by line but cant figure it out.
i've already made to split the string line by line, then count the <img> tags after it.
Example :
$string = "
some text <img src="" /> some text <img src="" /> some text <img src="" /> some text \n
some text <img src="" /> some text `<img src="" /> some text <img src="" /> some text ";
now my code is
first to split it line by line
$array = explode("\n", $string);
now count how many <img> tags are there in the first line of var string.
$first_line = $array['0'];
i was using preg_match() to get match for img tags.
$img_line = preg_match("#<img.+>#U", $array['0']);
echo count($img_line);
this wont work for me, in the $string there are 3 <img src=""> per line but my code gives me only 1.
any hint or tips are highly appreciated.
If you do a simple explode line by line, this will give you the count:
$explode = explode('<img ', $array[0]);
echo count($explode);
Got it..
After splitting the string per line.
$first_line = $array['0'];
$match = preg_match_all("#<img.+>#U", $first_line, $matches);
print_r($matches);
echo count($matches['0']);
the code above will return this..
Array
(
[0] => Array
(
[0] =>
[1] =>
[2] =>
)
)
3
You can try the following code:
<?php
$string = <<<TXT
some text <img src="" /> some text <img src="" /> some text <img src="" /> some text
some text <img src="" /> some text <img src="" /> some text <img src="" /> some text
TXT;
$lines = explode("\n", $string);
// For each line
$count = array_map(function ($v) {
// If one or more img tag are found
if (preg_match_all('#<img [^>]*>#i', $v, $matches, PREG_SET_ORDER)) {
// We return the count of tags.
return count($matches);
}
}, $lines);
/*
Array
(
[0] => 3 // Line 1
[1] => 3 // Line 2
)
*/
print_r($count);
Here, PREG_SET_ORDERstores the results in a single level (first capture to index $matches[0], second capture to index $matches[1]). Thus, we can easily retrieve the number of catches.
<?php
$string = 'some text <img src="" /> some text <img src="" /> some text <img src="" /> some text \n
some text <img src="" /> some text `<img src="" /> some text <img src="" /> some text ';
$count = preg_match_all("/<img/is", $string, $matches);
echo $count;
?>

replace all img tag with anchor tag

Replace all img tag with anchor tag where img src attribute value should be anchor tag href attribute value. I couldn't get idea how to write pattern to match whole and replace img tag and return anchor tag with href value as src attribute value of img tag in following process function.
I have tried below:
$pattern = '/<img[^>]+>/i';
$callback_fn = 'process';
$content = preg_replace_callback($pattern, $callback_fn, $string);
function process($matches)
{
print_r($matches);
return " <a href='http://mywebsite.com/".$matches[0]."'> <font color ='black' >View Image</font> </a>";
}
echo $content;
for example:
$string = "this is dummy string <img src="imageone.jpg" alt="" /> this is another sentesnces <img src="imagetwo.jpg" /> this is third one";
The output is:
this is dummy string View Image this is another sentesnces View Image this is third one
Here, View Image is link with
http://mywebsite.com/<img src="imageone.jpg" alt="" />
But I want this:
http://mywebsite.com/imageone.jpg
Try like this
$pattern = '/<img.+src=(.)(.*)\1[^>]*>/iU';
$callback_fn = 'process';
$string = 'this is dummy string <img src="imageone.jpg" alt="" /> this is another sentesnces <img src="imagetwo.jpg" /> this is third one';
$content = preg_replace_callback($pattern, $callback_fn, $string);
function process($matches)
{
return " <a href='http://mywebsite.com/".$matches[2]."'> <font color ='black' >View Image</font> </a>";
}
echo $content;
Also instead of <font> tag, use <span> because <font> is deprecated.

Strip tags, but keep the first one

How can I keep for example the first img tag but strip all the others?
(from a HTML string)
example:
<p>
some text
<img src="aimage.jpg" alt="desc" width="320" height="200" />
<img src="aimagethatneedstoberemoved.jpg" ... />
</p>
so it should be just:
<p>
some text
<img src="aimage.jpg" alt="desc" width="320" height="200" />
</p>
The function from this example can be used to keep the first N IMG tags, and removes all the other <img>s.
// Function to keep first $nrimg IMG tags in $str, and strip all the other <img>s
// From: http://coursesweb.net/php-mysql/
function keepNrImgs($nrimg, $str) {
// gets an array with al <img> tags from $str
if(preg_match_all('/(\<img[^\>]+\>)/i', $str, $mt)) {
// gets array with the <img>s that must be stripped ($nrimg+), and removes them
$remove_img = array_slice($mt[1], $nrimg);
$str = str_ireplace($remove_img, '', $str);
}
return $str;
}
// Test, keeps the first two IMG tags in $str
$str = 'First img: <img src="img1.jpg" alt="img 1" width="30" />, second image: <img src="img_2.jpg" alt="img 2" width="30">, another Img tag <img src="img3.jpg" alt="img 3" width="30" />, etc.';
$str = keepNrImgs(2, $str);
echo $str;
/* Output:
First img: <img src="img1.jpg" alt="img 1" width="30" />, second image: <img src="img_2.jpg" alt="img 2" width="30">, another Img tag , ... etc.
*/
You might be able to accomplish this with a complex regex string, however my suggestion would be to use preg_replace_callback, particularly if you are on php 5.3+ and here's why. http://www.php.net/manual/en/function.preg-replace-callback.php
$tagTracking = array();
preg_replace_callback('/<[^<]+?(>|/>)/', function($match) use($tagTracking) {
// your code to track tags here, and apply as you desire.
});

Categories