The
keepFirstImgs() function presented in this page can be used in PHP to keep the first Nr IMG tags into a string, and Strip all the other <img>s.
- The function receives the number of the first <img> tags to keep ($nrimg), and the string with the HTML text ($str); returns the string with the other IMG tags removed.
// Function to keep first $nrimg IMG tags in $str, and strip all the other <img>s
// From: https://coursesweb.net/php-mysql/
function keepFirstImgs($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;
}
- Example:
<?php
// Function to keep first $nrimg IMG tags in $str, and strip all the other <img>s
// From: https://coursesweb.net/php-mysql/
function keepFirstImgs($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" />,
and another image <img src="img_5.jpg" alt="imgage 5" width="30" /> ... etc.';
$str = keepFirstImgs(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 , and another image ... etc.
*/
?>
Daily Test with Code Example
HTML
CSS
JavaScript
PHP-MySQL
Which attribute is used in <img> tag for the address of the image?
href src rel<img src="http://coursesweb.net/imgs/webcourses.gif" width="191" height="63" alt="Courses-Web" />
Which CSS code hides the element on page?
display: none; display: inline; position: relative;#id {
display: none;
}
What instruction stops the execution of a while() or for() statement?
continue prompt() breakfor(var i = 0; i< 8; i++) {
if(i > 1) break;
alert(i);
}
Indicate the function that can create a constant.
define() include() defined()define("CONSTANT_NAME", "value");
echo CONSTANT_NAME;