John
John

Reputation: 12193

How to trim <br>, spaces and &nbsp from start and end of string

I'm trying to combine trimming of <br> or <br />, whitespaces and &nbsp;'s from the start and end of a string.

There are a few similar questions (here and here), but I couldn't get all 3 working in PHP.

Currently I have this; #(^(&nbsp;|\s)+|(&nbsp;|\s)+$)# needing combining with this: /(^)?(<br\s*\/?>\s*)+$/ but have no idea how to accomplish it. I'm using a PHP preg_replace.

Any help would be great, thanks.

Upvotes: 1

Views: 2328

Answers (2)

vooD
vooD

Reputation: 2921

Try this code.

<?php

$test_cases = array(
    "<br>&nbsp; spaces and br at the beginning&nbsp;",
    "<br /> spaces and br with / at the beginning &nbsp;",
    "<br> <br /> more examples &nbsp;",
    "&nbsp; even more tests <br />",
    "<br/> moaaaar <br> &nbsp;",
    "&nbsp;<br> it will not remove the <br> inside the text <br />&nbsp;"
);

$array = preg_replace('#^(<br\s*/?>|\s|&nbsp;)*(.+?)(<br\s*/?>|\s|&nbsp;)*$#i', '$2', $test_cases);

foreach($array as $item) {
    echo htmlspecialchars($item) . "<br>";
}

?>

Test cases are pretty much self explanatory.

edit:

I was having issues with the previous function when using large complex strings. Also I just wanted the end of the string trimmed this worked for me

preg_replace('#(<br\s*/?>)$#i', '', $string);

Upvotes: 5

timgavin
timgavin

Reputation: 5166

How about creating a function using a series of str_replace(), which is (to my understanding) twice as fast as preg_replace(), and you can easily extend the function to add more matches. just a thought...

$string = "My&nbsp;string<br />needs<br>a trim\n";

function trim_string($string) {
    $string = str_replace("<br>",'',$string);
    $string = str_replace("<br />",'',$string);
    $string = str_replace("&nbsp;",'',$string);
    $string = str_replace(" ",'',$string);
    return $string;
}
echo trim_string($string);

outputs Mystringneedsatrim

Upvotes: 0

Related Questions