How to replace all occurrences of two substrings with str_replace()?

寵の児 提交于 2019-12-02 12:52:34

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'] ));

Something like this:

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

Gives you:

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

Basically you are changing each space first to | then you are changing any that have two beside each other (||) to <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|/>.

EDIT with your code:

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

You can pass arrays to str_replace

$what[0] = '  ';
$what[1] = ' ';

$with[0] = '<br /><br />';
$with[1] = '|';

str_replace($what, $with, trim($result['garment_type'] ) )

To get around the issues with str_replace (space in <br /> being replaced with |) try strtr:

echo strtr(trim($result['garment_type']), array(' '=>'|', '  '=>'<br /><br />'));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!