0

In my MySQL database, the image links are saved in the format like http://www.old.com/image1.jpg. But I had to change the domains of the images and the new links appear like images.new.com/image1.jpg. I have been changing the images links with jQuery with the following function:

$(document).ready(function() {
    $('img').each(function() {
        var src = $(this).attr('src');;
        $(this).attr('src', src.replace('www.old', 'images.new'));
    });
});

But I am wondering is there any way to change part of the URL strings with PHP. I am getting the image URLs with the following PHP function.

<?php
   $imageQuery = $mysqli->query("SELECT imageURL FROM images WHERE album = 'UK' ORDER BY date ASC");
   $images = $imageQuery->fetch_all(MYSQLI_ASSOC);
   $images = array_chunk($images, 2);
   ?>
<div class="row">
   <div class="col-4" id="box1">
      <?php foreach (array_column($images, 0) as $image): ?>
      <img class="img-fluid" src="<?= $image['imageURL']; ?>">
      <?php endforeach; ?>
   </div>
   <div class="col-4" id="box2">
      <?php foreach (array_column($images, 1) as $image): ?>
      <img class="img-fluid" src="<?= $image['imageURL']; ?>">
      <?php endforeach; ?>
   </div>
</div>

With PHP how can I echo the new links for the images directly here in the img src? <img class="img-fluid" src="<?= $image['imageURL']; \\modified link here ?>">

2 Answers 2

4

PHP has it's own method for replacing strings, str_replace. The equivalent to your jQuery in PHP is:

str_replace('www.old', 'images.new', $image['imageURL'])

A better idea would be to update the values in your database.

An even better idea would be to not store the duplicate root URLs anywhere, and stitch them together in the application if you need absolute URLs, for some reason.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the solution. Seems like saving the URLs without root would be the best choice.
0

You could alternatively convert the text in the sql select statement:

SELECT REPLACE(imageURL, 'www.old', 'images.new') AS imageURL FROM ...

By using AS imageURL none of the rest of the code would need to change.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.