How to convert multiple
tag to a single
tag in php

后端 未结 9 1254
执念已碎
执念已碎 2020-12-03 02:03

Wanted to convert






into


相关标签:
9条回答
  • 2020-12-03 02:17

    You can do this with a regular expression:

    preg_replace("/(<br\s*\/?>\s*)+/", "<br/>", $input);
    

    This if you pass in your source HTML, this will return a string with a single <br/> replacing every run of them.

    0 讨论(0)
  • 2020-12-03 02:17

    A fast, non regular-expression approach:

    while(strstr($input, "<br/><br/>"))
    {
        $input = str_replace("<br/><br/>", "<br/>", $input);
    }
    
    0 讨论(0)
  • 2020-12-03 02:18

    without preg_replace, but works only in PHP 5.0.0+

    $a = '<br /><br /><br /><br /><br />';
    while(($a = str_ireplace('<br /><br />', '<br />', $a, $count)) && $count > 0)
    {}
    // $a becomes '<br />'
    
    0 讨论(0)
  • 2020-12-03 02:22

    User may enter many variants

    <br>
    <br/>
    < br />
    <br >
    <BR>
    <BR>< br>
    

    ...and more.

    So I think it will be better next

    $str = preg_replace('/(<[^>]*?br[^>]*?>\s*){2,}/i', '<br>', $str);
    
    0 讨论(0)
  • 2020-12-03 02:25

    You probably want to use a Regular Expression. I haven't tested the following, but I believe it's right.

    $text = preg_replace( "/(<br\s?\/?>)+/i","<br />", $text );
    
    0 讨论(0)
  • 2020-12-03 02:27

    Mine is almost exactly the same as levik's (+1), just accounting for some different br formatting:

    preg_replace('/(<br[^>]*>\s*){2,}/', '<br/>', $sInput);
    
    0 讨论(0)
提交回复
热议问题