php: replacing double
with

前端 未结 3 693
忘掉有多难
忘掉有多难 2021-01-17 14:22

i use nicEdit to write RTF data in my CMS. The problem is that it generates strings like this:

hello first line

this is a second line<
相关标签:
3条回答
  • 2021-01-17 15:12

    This approach will solve your problem:

    1. Split the string on <br> or <br />: you'll get an array of strings.
    2. Create a new string <p>.
    3. Loop on the array of 1, from the beginning to the end and remove all entries that are empty, until an entry that is not empty (break).
    4. Same as 3, but from the end to the beginning of the array.
    5. Loop on the array of 1, have an integer value A (default 0), which states that there is a single or double break.
      1. If the string is empty, increase the value of A and continue the loop.
      2. If the string is not empty:
        1. If the value of A is 1 or below, append a <br>.
        2. If the value of A is 2 or above, append a </p><p>.
      3. Append the content of the current entry (which is not empty).
      4. Set the value of A to 0.
    6. Append </p>

    A different approach: using Regular Expressions

    (<br ?/?>){2,}
    

    Will match 2 or more <br>. (See php.net on preg_split on how to do this.)

    Now, the same approach on step 2 and 3: loop on the array twice, once from the beginning up (0..length) and once from the end down (length-1..0). If the entry is empty, remove it from the array. If the entry is not empty, quit the loop.

    To do this:

    $array = preg_split('/(<br ?/?>\s*){2,}/i', $string);
    
    foreach($i = 0; $i < count($array); $i++) {
        if($value == "") {
            unset($array[$i]);
        }else{
            break;
        }
    }
    
    foreach($i = count($array) - 1; $i >= 0; $i--) {
        if($value == "") {
            unset($array[$i]);
        }else{
            break;
        }
    }
    
    $newString = '<p>' . implode($array, '</p><p>') . '</p>';
    
    0 讨论(0)
  • I think this should work for step #2 unless I am not understanding your scenario completely:

    $string = str_replace( '<br><br>', '</p><p>', $string );
    $string = str_replace( '<br /><br />', '</p><p>', $string );
    $string = str_replace( '<br><br />', '</p><p>', $string );
    $string = str_replace( '<br /><br>', '</p><p>', $string );
    
    0 讨论(0)
  • 2021-01-17 15:20

    This will work even if the two <br>s are on different lines (i.e. there is a newline or any whitespace between them):

    function replace_br($data) {
        $data = preg_replace('#(?:<br\s*/?>\s*?){2,}#', '</p><p>', $data);
        return "<p>$data</p>";
    }
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题