Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP mb_substr issues with truncate text

Tags:

php

phalcon

I have a function that truncates texts as follows:

public function truncateText($text, $val)
    {
        if(strlen($text) > $val){
            $content = mb_substr($text, 0, $val) . '...';
            return $content;
        } else {
            return $text;
        }
    }

I am having issues with multibyte characters. Even though i am using mb_substring i am still getting strange characters at the end of the text. My mb_internal_encoding is UTF-8.

An exemple would be as follows:

The string stored in the database is :

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent malesuada pretium justo, non posuere enim semper vel. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam iaculis nulla velit, eget accumááááá.</p>

When i run this string with the truncateText i get the following with and amp letter at the end:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent malesuada pretium justo, non posuere enim semper vel. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam iaculis nulla velit, eget accum&...

$this->tag->truncateText($text, 250);

However if i test it with the text directly without fetching it from the database and without the

tags then the truncate is good. I tried strip_tags in the string got from the database but still nothing.

var_dump of the mentioned string that is stored in the database:

string(925) "

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent malesuada pretium justo, non posuere enim semper vel. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam iaculis nulla velit, eget accumááááá.

"

var_dump of htmlspecialcharacters:

string(949) "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent malesuada pretium justo, non posuere enim semper vel. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam iaculis nulla velit, eget accum&aacute;&aacute;&aacute.</p> "

What am i missing here?

Many thanks, Trix

like image 486
trix87 Avatar asked Apr 19 '26 14:04

trix87


1 Answers

In your database adapter configuration add 'options':

use Phalcon\Db\Adapter\Pdo\Mysql;

$db = new Mysql(
     /* ... */
     'options'  => [
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"
      ]
   );  
like image 175
a_byte_late Avatar answered Apr 22 '26 13:04

a_byte_late



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!