Duc Truong
Duc Truong

Reputation: 42

Prevent <br> tag at end of input string with PHP

I want to eliminate the LAST <br> tag that can mess up my web display after the end of the user's input string. Apparently I messed something up on this simple task and stuck with it for some time now... Here is my code, please help me check what did I do wrong.

<?php
// Cut down Strange <br> tag
$content = "This is some string here<br>";
$content .= "And I want it to be on seperate line so yeah!!<br>";
$content .= "The last br tag is not suppose to be here<br>";
$checkBRtag = substr($content, -4);
if (strcmp($checkBRtag, "<br>") == 0)
    $result = substr($content, 0, -4);
?>

Strangely the result is that the string always get cut out the last 4 character without checking if it is <br> tag or not. Any idea?

Upvotes: 0

Views: 192

Answers (2)

arkascha
arkascha

Reputation: 42915

You general approach works for me, maybe you can simplify it, so that you always get the result in your variable $result:

<?php
$content = "This is some string here<br>";
$content .= "And I want it to be on seperate line so yeah!!<br>";
$content .= "The last br tag is not suppose to be here<br>";
$result = 
    (strcmp(substr($content, -4), "<br>") == 0) 
    ? substr($content, 0, -4) 
    : $content;

var_dump($result);

The output obviously is:

string(119) "This is some string here<br>And I want it to be on seperate line so yeah!!<br>The last br tag is not suppose to be here"


However I wonder if there is a better approach to this... Looking at the way you construct your $content in your code example it appears that you already have your text lines in an array like structure, so as separate lines. If so, then easiest would be not to append a <br> tag to each line at all, but to use the implode() function for this. That way you will not create that trailing tag in the first place, eliminating the need to remove it later...

Upvotes: 2

Ravi Hirani
Ravi Hirani

Reputation: 6539

You can use strip_tags

Specially in your case, If you know in which string you want to remove all HTML tags including with <br> tag.

$content = "This is some string here<br>";
$content .= "And I want it to be on seperate line so yeah!!<br>";
// below line remove all HTML tags from string with <br> tag.
$content .= strip_tags("The last br tag is not suppose to be here<br>");

Upvotes: 0

Related Questions