Jump to content

Trim tags from end of content


ShaolinF

Recommended Posts

Hi Guys,

 

Is there anyway I can use the trim() function to remove P tags from the beginning AND end ? So far I can only get it to remove one P tag but not both.

 

trim($content, '<p>');

 

I tried the following but it didn't work:

 

trim($content, '<p>..</p>');
trim($content,  array("<p>", "</p>"));

Link to comment
https://forums.phpfreaks.com/topic/202159-trim-tags-from-end-of-content/
Share on other sites

Since trim operates on characters rather than strings, this'll get rid of both tags, although if you have any other tags at the beginning or end it'll also remove parts of these.

trim($content, '</p>');

 

If you want to avoid damaging other tags, know that it's always <p> tags you're removing and they're only at the beginning and at the end, then you could try str_replace:

str_replace(array('<p>','</p>'),'',$content);

If you're more unsure about the content you're dealing with, you could use a regular expression (preg_replace, although you could use preg_match) to specifically target the beginning and end of the content.

This

<?php
str_replace(array('<p>','</p>'),'',$content);
?>

will replace those strings anywhere in $content, not just at the beginning or end.

 

The real solution would be to use regular expressions.

 

Something like this using preg_replace

<?php
$str = '<p>testing 123</p>';
$p = array('/^<p>/','/<\/p>$/');
$r = array('','');
echo 'Before: ' . strlen($str) . ' - ' . htmlentities($str) . "<br>";
$str = preg_replace($p,$r,$str);
echo 'after: ' . strlen($str) . ' - ' . htmlentities($str);
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.