如果对应值不为空则替换标签,否则不显示
我有一个代码:
$html = '<html>
<body>
<p><a href="[LINK]">[LINK]</a></p>
<p><img src="[IMAGE]" alt="something" /></p>
<p>Language specific string: [ANOTHER TAG]</p>
</body>
</html>';
$search = array('[LINK]', '[IMAGE]');
$replace = array($post['link'], $post['image']);
$html = str_replace($search, $replace, $html);
上面将用相应的 $post
值替换 [LINK]
和 [IMAGE]
- 当两个值都不是时,这很好空的。当一个或多个 $post
值为空时,我需要一种方法来隐藏相应的段落。任何人都知道什么是最有效的解决方案?$html
内容是使用 file_get_contents
加载的(上面只是其内容的说明)。
编辑:由于在 $html
中我也有“本地化”字符串,所以我宁愿使用不会强迫我替换整个段落的解决方案。有一个很好的答案使用了 DOM 操作,但作者已经删除了它......
I have a code:
$html = '<html>
<body>
<p><a href="[LINK]">[LINK]</a></p>
<p><img src="[IMAGE]" alt="something" /></p>
<p>Language specific string: [ANOTHER TAG]</p>
</body>
</html>';
$search = array('[LINK]', '[IMAGE]');
$replace = array($post['link'], $post['image']);
$html = str_replace($search, $replace, $html);
Above will replace [LINK]
and [IMAGE]
with corresponding $post
values - this is good when both values are not empty. I need a way to hide the corresponding paragraph when one or more $post
values are empty. Anyone has an idea what would be the most efficient solution?$html
content is loaded using file_get_contents
(the above is just an ilustration of its content).
EDIT: Since in the $html
I also have "localized" strings, I'd rather use the solution that doesn't force me to replace the whole paragraph. There was a good answer that used DOM manipulation but the author has deleted it...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
现在,
[LINK]
和[IMAGE]
如果存在,则替换为整个标记,如果不存在,则替换为空字符串。根据生成
$post
数组的方式,您可能需要使用empty()
以外的某些条件来确定它们是否存在,但您明白了。编辑
由于这些似乎是电子邮件模板文件,我建议使用 PHP 的模板功能,并将一些 PHP 代码放入模板中。
模板文件
PHP 脚本
Now
[LINK]
and[IMAGE]
are replace with the whole tag if they are present, and an empty string if not.Depending on how you generate the
$post
array, you may need to use some condition other thanempty()
to determine whether they are present, but you get the idea.EDIT
Since these appear to be email template files, I would suggest using the templating functionality of PHP and put some PHP code inside the templates.
Template file
PHP script
你可以这样做:
You can do: