我正在尝试找出如何在 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/