Как и предполагалось в Web Logic, я бы лучше попробовал расширение PHP DOM, особенно если вы работаете с целым HTML-документом. Вы можете передать некоторый фрагмент HTML в экземпляр PHP DOM или содержимое полной страницы HTML.
Один из примеров того, как сделать то, что вы предлагаете, если у вас просто есть строка элемента изображения, например <img src="../images/text.jpg" alt="test" />
, и вы хотите установить для атрибута src
его имя-файл изображения без расширения файла с префиксом cid:
<?php
$doc = new DOMDocument();
// Load one or more img elements or a whole html document from string
$doc->loadHTML('<img src="../images/text.jpg" alt="test" />');
// Find all images in the loaded document
$imageElements = $doc->getElementsByTagName('img');
// Temp array for storing the html of the images after its src attribute changed
$imageElementsWithReplacedSrc = array();
// Iterate over the found elements
foreach($imageElements as $imageElement) {
// Temp var, storing the value of the src attribute
$imageSrc = $imageElement->getAttribute('src');
// Temp var, storing the filename with extension
$filename = basename($imageSrc);
// Temp var, storing the filename WITHOUT extension
$filenameWithoutExtension = substr($filename, 0, strrpos($filename, '.'));
// Set the new value of the src attribute
$imageElement->setAttribute('src', 'cid:' . $filenameWithoutExtension);
// Save the html of the image element in an array
$imageElementsWithReplacedSrc[] = $doc->saveXML($imageElement);
}
// Dump the contents of the array
print_r($imageElementsWithReplacedSrc);
Печатает этот результат (используя PHP 5.2.x в Windows Vista):
Array
(
[0] => <img src="cid:text" alt="test"/>
)
<ч />
Если вы хотите установить значение атрибута src
равным значению атрибута alt с префиксом cid:
, посмотрите на это:
<?php
$doc = new DOMDocument();
// Load one or more img elements or a whole html document from string
$doc->loadHTML('<img src="../images/text.jpg" alt="test" />');
// Find all images in the loaded document
$imageElements = $doc->getElementsByTagName('img');
// Temp array for storing the html of the images after its src attribute changed
$imageElementsWithReplacedSrc = array();
// Iterate over the found elements
foreach($imageElements as $imageElement) {
// Set the new value of the src attribute
$imageElement->setAttribute('src', 'cid:' . $imageElement->getAttribute('alt'));
// Save the html of the image element in an array
$imageElementsWithReplacedSrc[] = $doc->saveXML($imageElement);
}
// Dump the contents of the array
print_r($imageElementsWithReplacedSrc);
Печать:
Array
(
[0] => <img src="cid:test" alt="test"/>
)
Надеюсь, это поможет вам начать. Это только примеры того, что делать с расширением DOM, ваше описание того, что вам нужно проанализировать (фрагменты HTML или полный документ HTML) и что вам нужно для вывода / хранения, было немного расплывчатым.