Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cut text after html a ending tag

Tags:

php

I have a comment system in my website and some users write very long comments, longer than 500 chars and I need to cut it after 200 and add the option "see more". The problem is that users can use <a>test</a> tags and in some cases the limit of 200 chars cuts the tag in the middle , like <a>t or <a or <a>test</ If any of the cases above happens, the limit should extend until the end of the html tag so ex <a>test</a>

I have this code:

function truncate($string,$length=200,$append="&hellip;") {
  $string = trim($string);

  if(strlen($string) > $length) {
    $string = wordwrap($string, $length);
    $string = explode("\n", $string, 2);
    $string = $string[0] . $append;
  }

  return $string;
}

Any idea how to make this?

Thanks

like image 869
zeeks Avatar asked Oct 19 '22 20:10

zeeks


1 Answers

Well, I think I did it. If anyone has any suggestion, feel free to modify this answer or comment.

function cut_text($string, $length = 350, $append = "&hellip;")
{

    $string = trim($string);
    $string_length = strlen($string);
    $original_string = $string;
    if ($string_length > $length) {
        $remaining_chars = $string_length - $length;
        if (strpos($string, '<') !== false && strpos($string, '>') !== false) {
            $string = wordwrap($string, $length);
            $string = explode("\n", $string, 2);
            $string = $string[0] . $append;
            $fillimi = substr_count($string, '<');
            $fundi = substr_count($string, '>');
            if ($fillimi == $fundi) {
                $string = $string;
            } else {
                $i = 1;
                while ($i <= $remaining_chars) {
                    $string = wordwrap($original_string, $length + $i);
                    $string = explode("\n", $string, 2);
                    $new_remaining_chars = $string_length - ($length + $i);
                    if ($new_remaining_chars > 0) {
                        $string = $string[0] . $append;
                    } else {
                        $string = $string[0];
                    }
                    $fillimi = substr_count($string, '<');
                    $fundi = substr_count($string, '>');
                    if ($fillimi == $fundi) {
                        $string = $string;
                        break;
                    }
                    $i++;
                }
            }
        } else {
            $string = trim($string);

            $string = wordwrap($string, $length);
            $string = explode("\n", $string, 2);
            $string = $string[0] . $append;

        }
    }
    return $string;
}
like image 103
zeeks Avatar answered Oct 22 '22 12:10

zeeks