php - 替换 HTML 图像的标题

标签 php regex image title

我正在尝试找出如何在 PHP 中替换图像的标题部分 (title="Title is here"),但我无法让它工作,所以有人可以吗有帮助吗?

标题实际上可以是任何内容,因此我需要找到 title"{anything here}" 并替换它(如下所示)。

我正在尝试使用 preg_replace(),但如果有更好的方法,我愿意接受建议。

我尝试了几种不同的变体,但我认为这并不太离谱 -

$pattern = '#^title="([a-zA-Z0-9])"$#';
$replacement = 'title="Visit the '.$service['title'].' page';
$service_image = preg_replace($pattern, $replacement, $service_image);

最佳答案

<?php

$html = '<img src="whatever.jpg" title="Anything">';


$dom = new DOMDocument;
$dom->loadHTML($html);
$img = $dom->getElementsByTagName("img")->item(0);
/** @var $img DOMElement  Now, $img contains the DOM note representing the image. */
$img->setAttribute("title", "Whatever you want here!");

/* Export the image alone (if not used like this,
 * you'd get a complete HTML document including head and body).
 *
 * This ensures you only get the image.
 */
echo $dom->saveXML($img);

请不要使用 HTML 正则表达式。这对你有用。

关于php - 替换 HTML 图像的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12052506/

相关文章:

java - 问号正则表达式 (Java)

javascript - 查找最后一个单词字符的索引(例如 :/\w/) in a string with JS

c# - 将鼠标悬停在图像控件上,例如 asp.net 中的 facebook 图片

php - 直接使用GET和POST有什么漏洞?

php - 如果数据库中的条目被删除,如何检查 PHP?

c# - 正则表达式而不是 string.replace 函数

image - 使用 extjs 在网格中显示图像

C++图像分析+按下按钮

php - 如果数组是使用 explode() 创建的,in_array() 将不再像预期的那样工作

php - 如何防止 PHP 中的 SQL 注入(inject)?