2

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);
4

2 に答える 2

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);

HTML の正規表現は使用しないでください。これはあなたのために働くでしょう。

于 2012-08-21T10:15:13.183 に答える
-2

このスニペットを使用してください:

$tag = '<img title="My Old Title" src="localhost"  alt="this is the alt"/>';
echo preg_replace('/(title)=("[^"]*")/i','title="My New Title"',$tag);
// <img title="My New Title" src="localhost" alt="this is the alt">
于 2012-08-21T10:20:37.910 に答える