且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何用 str_replace() 替换所有出现的两个子字符串?

更新时间:2023-02-18 09:27:48

数组的顺序很重要,否则你会得到 <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>'