stunnaman
stunnaman

Reputation: 911

php: trim <br> from the end of a string?

how can I trim <br>&nbsp; from the end of a string?

Upvotes: 0

Views: 2538

Answers (3)

antman3351
antman3351

Reputation: 496

Here's my solution that works like PHPs trim() but with words

/**
 * Trim one or more words from a string
 * @param string   $string
 * @param string[] $words
 */
public function mb_word_trim( string $string, array $words ) : string
{
    // Cache the word lengths
    $wordLens = [];
    foreach ( $words as $word )
    {
        $wordLens[ $word ] = mb_strlen( $word );
    }

   $stringLength = mb_strlen( $string );

   // Loop until no words were trimmed
   do
   {
       $wordWasTrimmed = false;
       foreach ( $words as $word )
       {
            // Trim the start
            if ( mb_substr( $string, 0, $wordLens[$word] ) === $word )
            {
                $string = mb_substr( $string, $wordLens[$word] );
                $stringLength = mb_strlen( $string );
                $wordWasTrimmed = true;
            }

           // Time the end
           if ( mb_substr( $string, $stringLength - $wordLens[$word] ) === $word )
           {
               $string = mb_substr( $string, 0, $stringLength - $wordLens[$word] );
               $stringLength = mb_strlen( $string );
               $wordWasTrimmed = true;
           }

           // If a word was trimmed we need to restart the check from the begging of the array of words
           if ( $wordWasTrimmed )
           {
               break;
           }
       }
   } while ( $wordWasTrimmed );

   return $string;
}

Quick PHPUnit test

public function test_mb_word_trim() : void
{
    $string = "<br>  &nbsp; have some 🍻🍻🍻 BEER <br> don't mess with inner text 🤣 &nbsp; 123  🤣 &nbsp;";
    $wordsToTrim = [ '<br>', '&nbsp;', ' ', '🤣' ]; // Note I've added an emoji to test multi byte

    $this->assertSame(
        "have some 🍻🍻🍻 BEER <br> don't mess with inner text 🤣 &nbsp; 123",
        \TGHelpers_String::mb_word_trim( $string, $wordsToTrim ),
    );
}

Upvotes: 0

Jeff Ober
Jeff Ober

Reputation: 5027

Slightly faster, if what you are trimming is constant:

$haystack = "blah blah blah <br>&"."nbsp;";
$needle = "<br>&"."nbsp;";
echo substr($haystack, 0, strrpos($haystack, $needle));

Upvotes: 1

matpie
matpie

Reputation: 17512

$Output = preg_replace('/'.preg_quote('<br>&'.'nbsp;').'$/i', '', $String);

Where $String is the input and $Output is the result.

Upvotes: 6

Related Questions