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

前端 未结 3 666
-上瘾入骨i
-上瘾入骨i 2021-01-28 13:20

Currently I have this code which replaces any double space with a
.

It works as expected:



        
相关标签:
3条回答
  • 2021-01-28 13:57

    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'] ) )
    
    0 讨论(0)
  • 2021-01-28 14:11

    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>'
    
    0 讨论(0)
  • 2021-01-28 14:18

    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 />'));
    
    0 讨论(0)
提交回复
热议问题