如何用 str_replace() 替换所有出现的两个子字符串? [英] How to replace all occurrences of two substrings with str_replace()?

查看:25
本文介绍了如何用 str_replace() 替换所有出现的两个子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有这个代码,它用 <br/> 替换任何双空格.

Currently I have this code which replaces any double space with a <br />.

它按预期工作:

<tr class="' . ($counter++ % 2 ? "odd" : "even") . '">
    <td>Garments:</td>
    <td>' . str_replace('  ', '<br /><br />', trim($result['garment_type'] ) ) . '</td>
</tr>

但是我想在同一行上执行另一个 str_replace() 用管道字符 | 替换任何单个空格.

However I want to do another str_replace() on the same line to replace any single spaces with a pipe character |.

我尝试复制代码,但这只会为我创建另一个 TD.

I tried duplicating the code but that just creates another TD for me.

任何帮助将不胜感激.

推荐答案

数组的顺序很重要,否则你会得到 <br|/> 而不是 <br/> 所以试试:

The order of the array does matter otherwise you will get <br|/> instead of <br /> so try:

str_replace(array(' ','||'), array('|','<br /><br />'), trim($result['garment_type'] ));

像这样:

echo str_replace(array(' ','||'), array('|','<br /><br />'), 'crunchy  bugs are so   tasty man');

给你:

crunchy<br /><br />bugs|are|so<br /><br />|tasty|man

基本上,您首先将每个空格更改为 | 然后将任何两个相邻的空格 (||) 更改为 <br/><br/>.

Basically you are changing each space first to | then you are changing any that have two beside each other (||) to <br /><br />.

如果你走另一条路,你会将两个空格更改为 <br/><br/> 然后你将单个空格更改为 | 并且在 <br/> 之间有一个空格,所以你最终得到 <br|/>.

If you go the other way, you will change two spaces to <br /><br /> and then you are changing single spaces to | and inbetween the <br /> there is a space, so you end up with <br|/>.

使用您的代码进行

'<tr class="' . ($counter++ % 2 ? "odd" : "even") . '">
    <td>Garments:</td>
    <td>' . str_replace(array(' ','||'), array('|','<br /><br />'), trim($result['garment_type'] )) . '</td>
</tr>'

这篇关于如何用 str_replace() 替换所有出现的两个子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆