How to trim all leading / trailing code using php

I am trying to remove all leading and trailing <br>

in a string using PHP.

Here's an example

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

      

I want to come back

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

      

I tried to do the following

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

      

But it doesn't delete them. How do I remove the new html code of a string?

+3


source to share


4 answers


Use preg_replace

with start ^

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 can also do trim()

it multiple times:

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

      

+5


source


This function does the job. Also applies to everything else.



//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;
}

      

+1


source


$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";
}

      

0


source


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

  • any tabs
  • any newlines
  • any
  • any
  • any tabs
  • any newlines

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;
}

      

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 :)

0


source







All Articles