javascript - 删除添加到 img 标签的参数

标签 javascript php wordpress

我有下面的图片,我想删除 jpg 之后的所有内容 (?resize=495%2C371&ssl=1)

https://i1.wp.com/atalantadigital.com/wp-content/uploads/2016/11/sampleimg.jpg?resize=495%2C371&ssl=1

我已经尝试过:

preg_match_all('/<img[^>]+>/i', $images);

foreach ($images[0] as $image) {
 str_replace('?resize=495%2C371&ssl=1', ' ', $image);
}

有一些图像添加了这些参数,我需要修复。我对 php 或 javascript 解决方案持开放态度,提前致谢!

我搜索了 stackoverflow,但没有找到答案。

最佳答案

Javascript 非常适合这项任务,因为我们可以通过 img.src 轻松选择所有 img 标签以及 src 属性.

这将从页面上的 img src 网址中删除所有查询字符串(? 及其后面的任何内容)。

// searches for all images on page
let images = document.getElementsByTagName("img")
// for each image
for (let img of images) {
    // replace source query string with nothing
    img.src = img.src.replace(/\?.+$/, "")
}

正则表达式说明:

\? Matches literal ?

.+$ Matches everything after it until end of input

下面显示了正则表达式的工作原理:

let img = new Image;
img.src = 'https://i1.wp.com/atalantadigital.com/wp-content/uploads/2016/11/sampleimg.jpg?resize=495%2C371&ssl=1';

img.src = img.src.replace(/\?.+$/, "");

console.log(img.src);

关于javascript - 删除添加到 img 标签的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56178356/

相关文章:

javascript - 仅隐藏循环中子级的父类

javascript - 如何在表中追加行时分配增量 ID?

javascript - 从带有 ID 的嵌套文档中检索数据

javascript - 是否有一种干净的方法来访问命名空间内的私有(private)变量

mysql - 首先 wpdb 插入到 mySql 新表不工作

Mysql查询将 "EXPIRED"插入到wordpress标题中

javascript - 在 iOS 的 UIAutomation UIATarget.onAlert 中处理自定义 javascript 异常

php - 查询数组中的输出值

php - 根据具有多个连接的最新日期选择行 -Code Ignitor

php - $this->headTitle 转义数据