I have a string ..... one .... and I have an array that contains images link
$my_string = '..... one ....';
$images = [
"0" => "image_url_1",
"1" => "image_url_2",
]
I need to replace the word one with these two images
my code:
$pdf_form = ".... <span>one</span> ....";
foreach ($images as $image) {
$pdf_form = Str::replace('one', '<img src="' . $image . '" />', $pdf_form);
}
dd($pdf_form);
The output is, I got just the first image only!
How can I print both images?
Do it like this
$replace_string="";
foreach ($images as $image) {
$replace_string.='<img src="' . $image . '" />';
}
$pdf_form = Str::replace('one', $replace_string, $my_string);
I see only twos bugs. 1) You use declare $image but never used. Change this: foreach ($images as $image) {to foreach ($images as $value) {
In a loop you will always override the value if you asign the value o variable by using =. Change this to .=
Update
$pdf_form .= \Stthis line is in your code wrong. You assign with = but you have to concat the strings with .=
$pdf_form = ".... <span>one</span> ....";
$images = ['pic1.png', 'pic2.png'];
foreach ($images as $image) {
$pdf_form .= \Str::replace('one', '<img src="' . $image . '" />', $pdf_form);
}
dd($pdf_form);
output
^ ".... <span>one</span> ........ <span><img src="pic1.png" /></span> ........ <span><img src="pic2.png" /></span> ........ <span><img src="pic1.png" /></span> .... ◀"
Take a look at the strtr function.
If I understand your question correctly, you want to display both images each with their own <img> tag.
$my_string = '<img src="one" />';
$images = [
"0" => "image_url_1",
"1" => "image_url_2",
]
$pdf_form = '';
foreach ($images as $image) {
$pdf_form = $pdf_form . strtr($my_string, ['one' => $image]);
}
Related
I have a list of image URLs stored in a database, separated by line breaks. The following PHP code displays them on my site:
$images = explode("\n", $value );
$value = '';
foreach ($images as $im){
$value .= '<img src="'. $im . '" style="max-width:1024px"/> <br />';
}
However, I want to hide some of the images behind a collapsible div if they contain a particular string.
Is it possible to write an if statement so $value changes to some HTML code displaying a collapsible div?
For example:
Rather than $value:
<img src="'. www.example.com/hiddenimage1.jpg . '" style="max-width:1024px"/> <br />
It would become:
<div class="collapsiblediv" style="etc etc"><img src="'. www.example.com/hiddenimage1.jpg . '" style="max-width:1024px"/> <br /></div>
However anything NOT containing "hiddenimage" would display as usual.
Is it possible?
You can use the strstr() function of PHP to search for a chunk of a string within a string.
Using this function, you can search for the value 'hiddenimage' within your foreach loop. Based on a conditional, you could then return either the collapsible <div> or the <img>
You could try this code
$images = explode("\n", $value );
$value = '';
foreach ($images as $im){
if(strstr( $im, 'hiddenimage' ) {
<div class="collapsiblediv" style="etc etc"><img src="'.
$im . '" style="max-width:1024px"/> <br
/></div>
} else {
$value .= '<img src="'. $im . '" style="max-width:1024px"/> <br />';
}
}
I'm trying to make a gallery using PHP. The images load properly, but the next and previous buttons don't seem to work. Clicking next on picture #1 brings you to picture #3 but clicking back on picture #3 bring you to picture #2 which is correct. How should I change my code to make it so both go in order?
<?php
function listPicturesInDir($dir) {
$dirname = "../pictures/photos/" . $dir . "/";
$images = glob($dirname . "*.jpg");
$previousPic = "null";
foreach ($images as $image) {
$next = next($images);
$name = str_replace(".jpg", "", $image);
$fp = strrpos($name, '/', 5) + 1;
$name = substr($name, $fp, strlen($name));
$id = str_replace(" ", "", $name);
echo '<img class="galleryPics" src="' . $image . '" alt = "' . $name . '" title="'. $name.'"/>';
echo '<div id="' . $id . '" class="modalDialog">';
echo '<div>';
if($previousPic !== "null"){
echo'<img src="../pictures/arrowLeft2.png" alt="Previous photograph" title= "Previous photograph" class="arrow"/> ';
}
if($next !== false){
$name_next = str_replace(".jpg", "", $next);
$fp_next = strrpos($name_next, '/', 5) + 1;
$name_next2 = substr($name_next, $fp_next, strlen($name_next));
$id_next = str_replace(" ", "", $name_next2);
echo'<img src="../pictures/arrowRight2.png" alt="Next photograph" title="Next photograph" class="arrow"/>';
}
echo 'X';
echo '<h2>' . $name . '</h2>';
echo '<img class="modalImg" src="' . $image . '" alt = "' . $name . '"/>';
echo '</div>';
echo '';
echo '</div>';
//echo $next;
$previousPic = $id;
}
}
?>
The problem is that you are using next($images) within a foreach ($images ...) statement, thus modifying the internal array pointer. This may lead to unexpected behavior, as pointed out in the documentation on foreach:
As foreach relies on the internal array pointer, changing it within the loop may lead to unexpected behavior.
This illustrates your problem, using foreach and next:
$images = array('one', 'two', 'three', 'four');
foreach ($images as $image) {
$next = next($images);
echo "$image => $next", PHP_EOL;
}
Output:
one => three
two => four
three =>
four =>
One may think that just replacing the next() with current() would help, but alas:
foreach ($images as $image) {
$next = current($images);
echo "$image => $next", PHP_EOL;
}
Output:
one => two
two => two
three => two
four => two
According to a comment on the foreach documentation page, there used to be a notice on said page stating that:
Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.
Don't know why that was removed, but if we use a reference for $image then it actually works (note the &):
foreach ($images as &$image) {
$next = current($images);
echo "$image => $next", PHP_EOL;
}
Output:
one => two
two => three
three => four
four =>
But then maybe an old school for loop just makes more sense:
for ($i = 0; $i < count($images); $i++) {
$nextIndex = $i + 1;
$next = ($nextIndex < count($images)) ? $images[$nextIndex] : null;
$image = $images[$i];
echo "$image => $next", PHP_EOL;
}
Output:
one => two
two => three
three => four
four =>
Output from PHP 5.5.20.
$images = sort(glob($dirname . "*.jpg"));
I try to dynamically populate an HTML page with 2 images, the first a full image and the second a reduced image, but as I can not do AND with a foreach.
In fact, the code is ok, but I want populate my HTML with twos pics of the same folder; but this code bring back all pictures, it doesn't no the diff between the Full image and the Thumbnail.
The script bring back all picture. My folder contain images with specific titles:
Full Image = *.jpeg
Thumbnail = *_Low.jpeg
I would like to be able to modify my code to insert the full in the first line and the thumbnail in the second line.
<?php
$dir = './style/images/art/mairie/';
$files = scandir($dir);
$images = array();
array().sort();
$nb = 1;
foreach($files as $file) {
if(fnmatch('*.jpg',$file)) {
$images[] = $file;
}
}
var_dump($images);
foreach ($images as $image) {
echo '<div class="cbp-item">'.'<a class="cbp-caption fancybox-media" data-rel="portfolio" href="style/images/art/mairie/'.$image.'">'."\n"
.'<div class="cbp-caption-defaultWrap">'.'<img src="style/images/art/mairie/'.$image.'" alt="" /> </div>'."\n"
.'<div class="cbp-caption-activeWrap">'."\n"
.'<div class="cbp-l-caption-alignCenter">'."\n"
.'<div class="cbp-l-caption-body">'."\n"
.'<div class="cbp-l-caption-title"><span class="cbp-plus">'.'</span></div>'."\n"
.'</div>'."\n"
.'</div>'."\n"
.'</div>'."\n"
.'<!--/.cbp-caption-activeWrap --> '."\n"
.'</a> </div>'."\n";
}
?>
for the second line I would like to bring back the reduced photo, so to have
<div class="cbp-caption-defaultWrap"><img
src="style/images/art/mairie/Maurine_Tric-7399_Low.jpg" alt="" />
</div>
$images
Part of my $images array would look like this:
$images = [
"0" => "Maurine_Tric-7399.jpg",
"1" => "Maurine_Tric-7399_Low.jpg",
"2" => "Maurine_Tric-7407.jpg",
"3" => "Maurine_Tric-7407_Low.jpg",
"4" => "Maurine_Tric-7414.jpg",
"5" => "Maurine_Tric-7414_Low.jpg",
];
Desired Output
I'm trying to add one of the URLs in my array with large images, and the other with its thumbnail which are being differentiated with _Low:
<div class="cbp-item"><a class="cbp-caption fancybox-media" data-rel="portfolio" href="style/images/art/mairie/Maurine_Tric-7399.jpg"> <div class="cbp-caption-defaultWrap"><img src="style/images/art/mairie/Maurine_Tric-7399_Low.jpg" alt="" /> </div>
Just use preg_match() instead of fnmatch(), matching only the thumbail images and marking the part before _Low.jpg as Subpattern.
Then you can easily construct the filename of both images from that stub:
<?php
$dir = './style/images/art/mairie/';
$files = scandir($dir);
$images = array();
array().sort();
$matches = NULL;
foreach ($files as $file) {
if (preg_match('/^(.+)_Low\.jpg$/', $file, $matches)) {
$images[] = $matches[1];
}
}
foreach ($images as $image) {
echo '<div class="cbp-item"><a class="cbp-caption fancybox-media" data-rel="portfolio" href="' . $dir . $image . '.jpg"> <div class="cbp-caption-defaultWrap"><img src="' . $dir . $image . '_Low.jpg" alt="" /></div>';
}
?>
If we wish to just add one URL for our images and one for their thumbs in the foreach, we might be able to define a $html variable and step by step add to it, then we would finally echo that, and our code would look like something similar to:
<?php
$html = '<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document sans titre</title>
</head>
<body>';
$html .= '<ul>';
$dir = './style/images/art/mairie/';
$files = scandir($dir);
$images = array();
$nb = 1;
foreach ($files as $file) {
if (fnmatch('*.jpg', $file)) {
$images[] = $file;
}
}
foreach ($images as $key => $image) {
if ($key % 2 == 0) {
$html .= '<div class="cbp-item">
<a class="cbp-caption fancybox-media" data-rel="portfolio" href="style/images/art/mairie/' . $image . '">
<div class="cbp-caption-defaultWrap"><img src="style/images/art/mairie/' . $images[$key + 1] . '" alt="" /> </div>
<div class="cbp-caption-activeWrap">
<div class="cbp-l-caption-alignCenter">
<div class="cbp-l-caption-body">
<div class="cbp-l-caption-title"><span class="cbp-plus"></span></div>
</div>
</div>
</div>
</a>
</div>';
}
}
$html .= '</ul></body></html>';
echo $html;
Modifications
What we are modifying here is that we add an if to run every other time.
if ($key % 2 == 0) {
}
We add $key var in our foreach and finally we have two image links which we replace one of them with $images[$key+1], which one of them is for thumbs:
$image
$images[$key+1]
What I'm trying to do is get the photo_id='.$pid.' of each photo for the link wrapped around them inside the foreach loop.
I tried $image['photo_id'] but that didn't work it just printed image symbols. I then wrapped a separate foreach loop around the current one and that duplicated the amount of images. I'm new to using the foreach loop with arrays and keys so still trying to get my head around it.
$images = array();
while ($rowhhh = mysqli_fetch_assoc($resulthhh)) {
$images[] = $rowhhh['photo_imagedata'];
$photo_id[] = $rowhhh['photo_id'];
}
foreach ($images as $image) {
if($photo_num==1){
echo '<img class="stream_images" style="width:200px;height:200px;object-fit:cover;margin:2px;padding:2px;" src="data:image/jpeg;base64,'. base64_encode($image) .'" />';
}else{
echo '<img class="stream_images" style="width:100px;height:100px;object-fit:cover;margin:2px;padding:2px;" src="data:image/jpeg;base64,'. base64_encode($image) .'" />';
}
}
Personally, I'd use the $images var as a multidimensional array to store the ID and the Data of each image. Then, you can access both of these bits of information easily in your foreach() loop.
$images = array();
while ($rowhhh = mysqli_fetch_assoc($resulthhh)) {
$imageArray = array(
'data' => $rowhhh['photo_imagedata'],
'id' => $rowhhh['photo_id']
);
$images[] = $imageArray;
}
foreach ($images as $image) {
if($photo_num==1){
echo '<img class="stream_images" style="width:200px;height:200px;object-fit:cover;margin:2px;padding:2px;" src="data:image/jpeg;base64,'. base64_encode($image['data']) .'" />';
}else{
echo '<img class="stream_images" style="width:100px;height:100px;object-fit:cover;margin:2px;padding:2px;" src="data:image/jpeg;base64,'. base64_encode($image['data']) .'" />';
}
}
Okay, I am currently using this:
<?php
$dirname = "cards/collecting/";
$images = glob($dirname."*.png");
foreach ($images as $image) {
$title = pathinfo($image);
echo '<img class="deck" src="'.$image.'" alt="'. $title['filename'].'" title="'.$title['filename'].'">';
}
?>
This pulls a bunch of small images out of a folder and displays them. It works great, but I want there to be a after each 5th image, so it doesn't stretch across the entire div in which the image are being shown. I'm unsure what I need to add to do this.
Thanks in advance!
Using the index, you can write <br/> every time the index+1 is a multiple of 5: index 4, 9, 14, etc... Notice that I use $i=> in the foreach to get the value of $i.
<?php
$dirname = "cards/collecting/";
$images = glob($dirname."*.png");
foreach ($images as $i=>$image) {
$title = pathinfo($image);
echo '<img class="deck" src="'.$image.'" alt="'. $title['filename'].'" title="'.$title['filename'].'">';
if(($i+1)%5 == 0) echo '<br/>';
}
?>
The easiest way is use array_chunk.
array_chunk
array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )
Chunks an array into arrays with size elements. The last chunk may contain less than size elements
Code example:
$dirname = "cards/collecting/";
$images = glob($dirname."*.png");
$grp = array_chunk($images, 5, true);
foreach ($grp as $items) {
echo '<div class="item_grp">';
foreach ($items as $image) {
$title = pathinfo($image);
echo '<img class="deck" src="'.$image.'" alt="'. $title['filename'].'" title="'.$title['filename'].'">';
}
echo '</div>';
}