如何用不同的内容替换多个html标记的一部分取决于给定的数据

时间:2015-07-10 17:23:29

标签: php html

我需要替换多个html标签。示例代码如下:

$html = "<p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
  <visualcontent imgid='1' type='jpg'></visualcontent>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
  <visualcontent imgid='2' type='png'></visualcontent>
</p>";

我需要的输出是:

$html = "<p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
  <img src='1.jpg'>


  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
  <img src='2.png'>
</p>";

如果你看到:

<visualcontent imgid='x' type='x'></visualcontent> 

被替换为图片标记。我对如何做到这一点毫无头绪。请帮忙。

由于

1 个答案:

答案 0 :(得分:1)

您可以使用Simple HTML DOM Parser

轻松完成此操作

以下是:

<?php
include('simple_html_dom.php');

$htmlString = "<p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
  <visualcontent imgid='1' type='jpg'></visualcontent>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
  <visualcontent imgid='2' type='png'></visualcontent>
</p>";

$html = str_get_html($htmlString);

foreach($html->find('visualcontent') as $v){
    $src = $v->imgid;
    $type = $v->type;

    $v->outertext = '<img src="'. $src .'.'.$type.'" />';
}

$output = $html->save();

print $output;

$html->clear();
unset($html);

将准确地告诉你你的目标:

  

<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. <img src="1.jpg" /> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. <img src="2.png" /> </p>