Не нравятся результаты поиска? Попробуйте другой поиск!
DLE FAQ » Все вопросы » Хаки » Вопрос по кастому (форматирование текста)

Вопрос по кастому (форматирование текста)


     15.04.2014    Все вопросы » Хаки    2782

вопрос
Есть в Dle замечательный тег {short-story limit=число}, который выводит краткую новость, обрезанную до определенного количества символов, но есть одна беда: при выводе текста теряется его форматирование.
Задача состоит в том что бы состряпать новый тег, который будет обрезать текст но в то же время сохранять основное форматирование текста (перенос строки, выделение жирным).

2 комментария

dj-avtosh
PHP-developer

dj-avtosh - 15 апреля 2014 04:36 -

Вот, написал код, автоматом сохраняет теги, и закрывает открытые, что бы не ехала верстка.



/**
* Smarty Crop Text
* :: Метод режет текст сохраняя теги
* @author Elkhan I. Isaev <elhan.isaev@gmail.com>
*/

function smartyCropText (  $text = null, $textLength = 0, $charset = 'UTF-8' )
{

    if ( ! empty ( $text ) && 0 <> $textLength )
    {
        preg_match ( '~^(?>(?><[^>]*>\s*)*[^<]){0,' . $textLength . '}(?=\s)~s', $text, $newTextArray );
        return ( isset ( $newTextArray[0] ) ? close_tags ( $newTextArray[0], $charset  ) : $text );
    }

    return $text;

}


/**
* Auto Close Open Tags
* :: Метод закрывает все открытые теги
* @author artkiev
* @author Optimize: Elkhan I. Isaev <elhan.isaev@gmail.com>
*/

function close_tags ( $content, $charset = 'UTF-8', $ignored_tags = array( 'br', 'hr', 'img' )  )
{

    $position  = 0;
    $open_tags = array();

    while ( ( $position = strpos($content, '<', $position) ) !== FALSE )
    {

        if ( preg_match( "|^<(/?)([a-z\d]+)\b[^>]*>|i", substr ( $content, $position ), $match ) )
        {

            $tag = strtolower ( $match[2] );

            if ( FALSE === in_array ( $tag, $ignored_tags ) )
            {
                    if ( isset ( $match[1] ) && '' == $match[1] ) : isset ( $open_tags[$tag] ) ? $open_tags[$tag]++ : $open_tags[$tag] = 1; endif;
                    if (isset($match[1]) AND $match[1] == '/')    : isset ( $open_tags[$tag] ) && $open_tags[$tag]--;                       endif;
            }

            $position += mb_strlen ( $match[0], $charset );

        } else $position++;

    }

    foreach ( $open_tags as $tag => $count_not_closed ) : $content .= str_repeat( "</{$tag}>", $count_not_closed ); endforeach;
        
    return $content;
}



Использование:




$text = <<<HTML
<div align='center'></div>
<div align='left'><b>Название: </b>Aspirin Jah - Понедельник <br />
    <b>Жанр музыки:</b> Rap, Hip Hop <br />
    <b>Год выхода: </b>2014<br />
    <b>Время звучания:</b> 00:25:26<br />
    <b>Формат / Качество:</b> mp3 / 320 kbps<br />
    <b>Размер:</b> 55Мб<br />
    </div>
HTML;



echo smartyCropText ( $text, 150, $config['charset'] );

https://elkhan.ru
По заказам пишем сюда: @Rud00y

ЯД: 41001679231462
Заказы в telegram (ремонт модулей, оптимизация нагрузок и т.п.):
В телегу писать сразу задачу и бюджет.

dj-avtosh
PHP-developer

dj-avtosh - 15 апреля 2014 04:39 -

Для вашего примера юзаем так:

if ( preg_match( "#\\{short-story limit=['\"](.+?)['\"]\\}#i", $tpl->copy_template, $matches ) ) {
        $count= intval($matches[1]);
    
        $row['short_story'] = strip_tags( $row['short_story'], "<br>" );
        
        if( $count AND dle_strlen( $row['short_story'], $config['charset'] ) > $count )
        {
                        
                   $row['short_story'] = smartyCropText ( $row['short_story'], $count, $config['charset'] );
                    
        }

    
        $tpl->set( $matches[0], $row['short_story']);
    
    }








Не забыв при этом в functions.php





/**
* Smarty Crop Text
* :: Метод режет текст сохраняя теги
* @author Elkhan I. Isaev <elhan.isaev@gmail.com>
*/

function smartyCropText (  $text = null, $textLength = 0, $charset = 'UTF-8' )
{

    if ( ! empty ( $text ) && 0 <> $textLength )
    {
        preg_match ( '~^(?>(?><[^>]*>\s*)*[^<]){0,' . $textLength . '}(?=\s)~s', $text, $newTextArray );
        return ( isset ( $newTextArray[0] ) ? close_tags ( $newTextArray[0], $charset  ) : $text );
    }

    return $text;

}


/**
* Auto Close Open Tags
* :: Метод закрывает все открытые теги
* @author artkiev
* @author Optimize: Elkhan I. Isaev <elhan.isaev@gmail.com>
*/

function close_tags ( $content, $charset = 'UTF-8', $ignored_tags = array( 'br', 'hr', 'img' )  )
{

    $position  = 0;
    $open_tags = array();

    while ( ( $position = strpos($content, '<', $position) ) !== FALSE )
    {

        if ( preg_match( "|^<(/?)([a-z\d]+)\b[^>]*>|i", substr ( $content, $position ), $match ) )
        {

            $tag = strtolower ( $match[2] );

            if ( FALSE === in_array ( $tag, $ignored_tags ) )
            {
                    if ( isset ( $match[1] ) && '' == $match[1] ) : isset ( $open_tags[$tag] ) ? $open_tags[$tag]++ : $open_tags[$tag] = 1; endif;
                    if (isset($match[1]) AND $match[1] == '/')    : isset ( $open_tags[$tag] ) && $open_tags[$tag]--;                       endif;
            }

            $position += mb_strlen ( $match[0], $charset );

        } else $position++;

    }

    foreach ( $open_tags as $tag => $count_not_closed ) : $content .= str_repeat( "</{$tag}>", $count_not_closed ); endforeach;
        
    return $content;
}


https://elkhan.ru
По заказам пишем сюда: @Rud00y

ЯД: 41001679231462
Заказы в telegram (ремонт модулей, оптимизация нагрузок и т.п.):
В телегу писать сразу задачу и бюджет.

Чтобы комментировать - войдите или зарегистрируйтесь на сайте

Похожие вопросы

наверх