Jump to content

Truncate – Remove <figure> and it’s contents


Falk
 Share

Recommended Posts

Hi Forum!

I have the following content in a ckeditor body-field:

<figure class="align_right"><img alt="some random alt text" src="path/to/image-file" />
<figcaption>some random caption text</figcaption>
</figure>

<p>some random text</p>

I use 

$text = $sanitizer->truncate($page->body, [
	'type' => 'sentence',
	'maxLength' => 400,
	'visible' => true
]);
$content = "<p>";
$content .= $text;
$content .= "</p>";

echo $content;

to output the body-field in my template, which results in…

<p>some random caption text some random text</p>

Is there any way to tell $sanitizer->truncate to skip/remove/ignore anything that’s inside a <figure> Tag, so that I get rid of the part "some random caption text"?

 

 

Link to comment
Share on other sites

@Falk

$string = '<figure class="align_right"><img alt="some random alt text" src="path/to/image-file" />
<figcaption>some random caption text</figcaption>
</figure>
<p>some random text</p>';

$purifier = $sanitizer->purifier();
$purifier->set('HTML.ForbiddenElements', array('figure'));
$purifier->set('Core.HiddenElements', array('figure' => true));
$clean = $purifier->purify($string);
$text = $sanitizer->truncate($clean, [
	'type' => 'sentence',
	'maxLength' => 400,
	'visible' => true
]);
$content = "<p>";
$content .= $text;
$content .= "</p>";

d($content);

chrome_9yMPLxG9ry.jpg.517071ddeb0b8690ce1aab307980aad1.jpg

  • Like 2
  • Thanks 1
Link to comment
Share on other sites

Hi Zeka,

ahh, I missed the purifier! Thanks for this solution.

After messing around with regex, I found out that this is working too:

$content = preg_replace('/<figure[^>]*>([\s\S]*?)<\/figure[^>]*>/', '', $page->body);
$text = $sanitizer->truncate($content, [
	'type' => 'sentence',
	'maxLength' => 400,
	'visible' => true
]);
echo '<p>' . $text . '</p>';

Thanks again!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...