如何解析散布在HTML DOMDocument文本中的图像?

问题描述:

我试图解析一个字段,其中有一些字母和数字的图像。它可能是段落的首字母,该字母的幻想图像,或者可能是字母或数字在文本中间有图像替换。例如,短语如何解析散布在HTML DOMDocument文本中的图像?

"Four scores and 7 years ago" 

<img src=/img/F.png>our scores and <img src=/img/7.png"> years ago 

用图像替换一些字母和数字。

我正确地能够解析字母或数字,我想用文本字段替换图像,但我不太明白我应该如何去做。这是基于关闭的例子在PHP文档:

if (! strcmp('Text Field', $label)) { 
    $img_tags = $divs->item($i + 1)->getElementsByTagName('img'); 
    $num_images = $img_tags->length; 

    for ($img = 0; $img < $num_images; $img++) { 
     if ($img_tags->item($img)->hasAttributes()) { 
      $img_tag = $img_tags->item($img)->getAttribute('src'); 
      if (preg_match('/name=([a-zA-Z0-9])/', $img_tag, $matches)) { 
       // XXX So here I have $matches[1] which contains the letter/number I want inserted into the parent node in the exact place of the <img> tag 
       $replacement = $page->createTextNode($matches[1]); 
       $img_tags->item($img)->parentNode->replaceChild($replacement, $img_tags->item($img)); 
      } 
     } 
    } 
} 

扩展的例子:

可以说,我打出一行这样:

<div class="label">Title</div> 

我知道下一个字段将是文本字段

<div class="value"> 
    <img src=/img/F.png>our scores and <img src=/img/7.png"> years ago 
</div> 

我试图抓住段落并将图像转换为我从图像名称解析出的字母。

+0

请给这里的html代码的文本示例。这会让问题更容易理解。 – arkascha

+0

当然,可以说我打出一行这样: ''

Title
我知道下一场会是一个文本字段 ''
our scores and years ago
我试图抓住段落,并把图像变成字母我从图像名称解析。 – user1703991
+0

感谢您的补充信息。然而,我们仍然无法理解你正在尝试做什么。你给的html标记和你上面引用的php代码之间的连接在哪里? $ label,$ divs从哪里来?缺少重要信息,因此无法给出答案。 – arkascha

可能使用str_replace是更好的方法。

$source = "<img src=/img/F.pNg>our scores and <img src=/img/7.png\"> years ago"; 

preg_match_all("/<.*?[\=\/]([^\/]*?)\.(?:png|jpeg).*?>/i", $source, $images); 

$keys = array(); 
$replacements = array(); 

foreach($images[0] as $index => $image) 
{ 
    $keys[] = $image; 
    $replacements[] = $images[1][$index]; 
} 

$result = str_replace($keys, $replacements, $source); 

// Returns 'Four scores and 7 years ago' 
print($result . PHP_EOL);