Reputation: 12193
I'm trying to combine trimming of <br>
or <br />
, whitespaces and
'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; #(^( |\s)+|( |\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
Reputation: 2921
Try this code.
<?php
$test_cases = array(
"<br> spaces and br at the beginning ",
"<br /> spaces and br with / at the beginning ",
"<br> <br /> more examples ",
" even more tests <br />",
"<br/> moaaaar <br> ",
" <br> it will not remove the <br> inside the text <br /> "
);
$array = preg_replace('#^(<br\s*/?>|\s| )*(.+?)(<br\s*/?>|\s| )*$#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
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 string<br />needs<br>a trim\n";
function trim_string($string) {
$string = str_replace("<br>",'',$string);
$string = str_replace("<br />",'',$string);
$string = str_replace(" ",'',$string);
$string = str_replace(" ",'',$string);
return $string;
}
echo trim_string($string);
outputs Mystringneedsatrim
Upvotes: 0