Img link remover php script

Simple php-script help with fast remove img link in database, in my case - Drupal 9 body field.

In this case we remove all img link that make src start with - https://www.domain.com/img_folder


<?php
$conn = new mysqli("localhost", "user", "pass", "db_name");
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT entity_id, body_value FROM node__body WHERE body_value LIKE '%https://www.domain.com/img_folder%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
   while($row = $result->fetch_assoc()) {
       $new_body_value = preg_replace('/<img[^>]*src="https:\/\/www\.domain\.com\/img_folder[^"]*"[^>]*>/', '', $row["body_value"]);
       $entity_id = (int)$row["entity_id"];
       $new_body_value_escaped = $conn->real_escape_string($new_body_value);
       $update_sql = "UPDATE node__body SET body_value = '$new_body_value_escaped' WHERE entity_id = $entity_id";
       if (!$conn->query($update_sql)) {
           echo "Error updating record: " . $conn->error;
       }
   }
}
$conn->close();
?>

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
The comment language code.