正则表达式找到图像路径文件中的图像标签
问题描述:
我正在寻找一个正则表达式,在一个图像标记(SRC)找到所有图像路径和CID变换所有图像路径:文件名正则表达式找到图像路径文件中的图像标签
<img src="../images/text.jpg" alt="test" />
到
<img src="cid:test" alt="test" />
感谢您的帮助
克里斯
答
随着Web逻辑的建议,我宁愿给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);
为前缀的文件扩展名
一个例子
打印这个结果(在Windows Vista上使用PHP 5.2.x):
Array
(
[0] => <img src="cid:text" alt="test"/>
)
如果你想设置的值在src
属性由前缀cid:
alt属性的值,看看这个:
<?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文档)以及您需要输出/存储的内容有点模糊。
只是为了澄清:src =“../ images/text.jpg”应该是src =“../ images/test.jpg”或者你真的想要将alt属性的值插入为cid吗? – Max 2010-05-23 08:29:47