简体   繁体   中英

How to trim all leading/trailing <br> code using php

I am trying to remove all leading and trailing <br> in a string using PHP.

Here is an example

<br><br>
Hello<br>
World<br>
<p>This is a message<br>...</p>
<br><br><br><br>

I want to return

Hello<br>
World<br>
<p>This is a message<br>...</p>

I tried to do the following

echo trim($str, '<br>');

But it does not remove them. How can I remove the new line html code?

Use preg_replace with the beginning ^ and end $ anchors:

$string = preg_replace('/^(<br>){0,}|(<br>){0,}$/', '', $string);

Or for multiple lines:

$string = preg_replace('/^(<br>){0,}|(<br>){0,}$/m', '', $string);

You could also trim() it multiple times:

while($string !== ($string = trim($string, '<br>'))){}

This function does the job. Also applicable to anything else really.

//remove all leading and trailing occurences of needle ($n) from haystack ($h)
function trimAll($h, $n){
    if(!$h = trim($h,$n)){ 
        trimAll($h, $n);
    }
    return $h;
}

I wrote this function that will do the job a little better as it gives me more flexibility on what characters to remove and when this function by default will first remove the leading/trailing characters in order:

  1. any tabs
  2. any new lines
  3. any
  4. any
  5. any tabs
  6. any new lines

function trimString($str, $myList = array("\t","\n", "<br>","<br />", "\t","\n") ){
    if( ! is_array($myList) ){
        $charsToTrim[] = $chr;
    } else {
        $charsToTrim = $myList;
    }

    foreach($charsToTrim as $chr){
        $len = strlen($chr);
        $nlen = $len * -1;

        while( substr($str, 0, $len) == $chr){
            $str = trim(substr($str, $len));
        }

        while( substr($str, $nlen) == $chr){
            $str = trim(substr($str, 0, $nlen));
        }
    }

    return $str;
}

to use

// default use case    
echo trimString($message);

or

//remove only one string
echo trimString($message, '<br>');  // remove only the leading training '<br>'

or

//remove more than 1 string in order
echo trimString($message, array('<br>'<br />') );

I hope this helps someone out there :)

$p=array(
  '<br><br>',
  'Hello<br>',
  'World<br>',
  '<p>This is a message<br>...</p>',
  '<br><br><br><br>'
);
function trimdeluxe($str, $sub)
{
    $parts=explode($sub, $str);
    for ($x=0; $x<2; $x++) {
            foreach ($parts as $i=>$v) {
                    if (!strlen($v)) {
                            unset($parts[$i]);
                    } else {
                            break;
                    }
            }
            $parts=array_reverse($parts);
    }
    return implode($sub,$parts);
}

foreach ($p as $str) {
    print $str . ' -> ' . trimdeluxe($str, '<br>') . "\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM