替换HTML图像的标题

Dav*_*ard 2 php regex image title

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

标题可以是字面上的任何东西,所以我需要找到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);
Run Code Online (Sandbox Code Playgroud)

Mad*_*iha 6

<?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);
Run Code Online (Sandbox Code Playgroud)

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