Search code examples
phplaravellaravel-bladefakerhtmlpurifier

PHP Cut String On Character Limit


I'm creating a Blog that uses a Faker Factory to generate Demo Data. I have a Post Model which is generated that has a body field which contains randomly generated HTML as well as a text field which is created by stripping the tags from the body and limiting the data received to 512 characters. str_limit works fine it is just that I need to cut the text off on a word while keeping it in the 512 limit.

This is my factory:

<?php

use Faker\Generator as Faker;

$factory->define(Provar\Forum\Post::class, function (Faker $faker) {

   $randomHTML = Purifier::clean($faker->randomHtml(2,3));

   $trimedHTML = strip_tags($randomHTML);

   return [
      'body' => $randomHTML,
      'text' => str_limit($trimedHTML, 509, '...')
   ];

});

Any help is appreciated. <3


Solution

  • You could try with something like this, but this might cut the last word

    substr($trimedHTML, 0, 512) . '...'
    

    If you don't want the last word cut, you might do something like this, but will not give you exactly 512 characters always, cause next word might be to big...

    $text=$trimedHTML;
    if (preg_match('/^.{1,512}\b/s', $trimedHTML, $match))
    {
        $text=$match[0] . ( strlen($match[0]) < strlen($trimedHTML) ? "..." : "" );
    }
    

    And use the $text, variable instead of str_limit($trimedHTML, 509, '...')

    This code is literally the same as the one in this answer: Making sure PHP substr finishes on a word not a character Though this might be considered "another question" so...