Counting string length with HTML numbered objects in PHP

I would like to calculate the length of a string with PHP. The string contains the numbers of HTML objects that inflate the number of characters that are counted: dash – which is considered 7 when I want it to be considered 1.

How to convert objects with the html number to a form where special characters are taken into account only with a length of 1?

Example line:

 Goth-Trad – ‘Cosmos’ 

Code:

 $string = html_entity_decode('Goth-Trad – ‘Cosmos’'); echo strlen($string); 

produces "38" when I search for "20". What is going wrong?

+4
source share
3 answers

You can use this:

 $html = 'Goth-Trad – ‘Cosmos’'; echo strlen(utf8_decode(html_entity_decode($html, ENT_COMPAT, 'utf-8'))); 
+3
source

Just decode it and count decoded?

 $string = html_entity_decode("Goth-Trad – ‘Cosmos’",ENT_QUOTES,"UTF-8"); echo strlen($string); 
+3
source

Try using the following encoding function:

 <?php $string='Goth-Trad &#8211; &#8216;Cosmos&#8217;'; echo html_entity_text_length($string); // Calling the function //html_entity_text_length function start function html_entity_text_length($string){ preg_match_all("/&(.*)\;/U", $string, $pat_array); $additional=0; foreach ($pat_array[0] as $key => $value) { $additional += (strlen($value)-1); } $limit+=$additional; return strlen($string)-$limit; } //html_entity_text_length function end ?> 
-1
source

Source: https://habr.com/ru/post/1388937/


All Articles