在PHP中使用相关值进行HTML解析

问题描述:

I have used Laravel 5.1 for my current project. In this project, I have a text area input field where user can insert HTML with predefined placeholder. Please take a look:

<div id="recommend">
  <div class="title"><p>Title</p></div>
    #{item}
  <div class="layout">
    <div class="item">
      <a href="#{url}" class="rcm11"><img border="0" alt="#{name}" src="#{image}"></a>
    </div>
  </div>
  #{/item}
</div>

I saved it to my database. when a user request a HTML, I have given this html by replacing placeholder with proper value. On the above HTML #{item}, #{url} etc. are place holders. I need to parse this place holders and replace with proper value. In Laravel or PHP, how can I do it? If anyone have a answer please let me know.

我已将Laravel 5.1用于我当前的项目。 在这个项目中,我有一个文本区域输入字段,用户可以在其中插入带有预定义占位符的HTML。 请看一下: p>

 &lt; div id =“recommended”&gt; 
&lt; div class =“title”&gt;&lt; p&gt; Title&lt; / p&gt;  &lt; / div&gt; 
#{item} 
&lt; div class =“layout”&gt; 
&lt; div class =“item”&gt; 
&lt; a href =“#{url}”class =  “rcm11”&gt;&lt; img border =“0”alt =“#{name}”src =“#{image}”&gt;&lt; / a&gt; 
&lt; / div&gt; 
&lt; / div&gt;  
#{/ item} 
&lt; / div&gt; 
  code>  pre> 
 
 

我已将其保存到我的数据库中。 当用户请求HTML时,我通过用适当的值替换占位符来给出这个html。 在上面的HTML#{item}上,#{url}等是占位符。 我需要解析这个占位符并用适当的值替换。 在Laravel或PHP中,我该怎么办? 如果有人有答案,请告诉我。 p> div>

You can use str_replace() by giving 2 arrays

$placeHolder = array('#{item}'  , '#{url}'  , ...);
$values      = array('itemValue', 'urlValue', ...);

print_r (str_replace($placeHolder, $values, $template));

Or strtr()

   $trans = array('#{item}' => 'itemValue', 
                  '#{url}'  => 'urlValue' , 
                   ...);

  print_r (strtr($template, $trans));