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

两盒软妹~` 提交于 2019-12-20 06:15:39

问题


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

It works as expected:

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

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

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

Any help would be appreciated.


回答1:


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>'



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/45577371/how-to-replace-all-occurrences-of-two-substrings-with-str-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!