Cut

Подскажите, как организовать так, чтобы тег <сut> ставился автоматом после загруженного изображения? или выдавалось какое нибудь сообщение, что вы не поставили данный тег.

11 комментариев

avatar
присоединяюсь к вопросу, или такой вариант что бы выставлять в конфиге после скольких знаков автоматом после постинга выставлялся бы автоматом <сut> к примеру ставишь в конфиге 200 знаков…
avatar
avatar
я нашел функцию, но еще не тестил ее.
Попробую сегодня прикрутить к своему плагину.
/**
 * Truncates text.
 *
 * Cuts a string to the length of $length and replaces the last characters
 * with the ending if the text is longer than length.
 *
 * @param string  $text String to truncate.
 * @param integer $length Length of returned string, including ellipsis.
 * @param string  $ending Ending to be appended to the trimmed string.
 * @param boolean $exact If false, $text will not be cut mid-word
 * @param boolean $considerHtml If true, HTML tags would be handled correctly
 * @return string Trimmed string.
 * Modified by kvs, http://www.securityhacking.tk
 */
    function truncate($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true) {
        if ($considerHtml) {
            // if the plain text is shorter than the maximum length, return the whole text
            if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
                return $text;
            }
            // splits all html-tags to scanable lines
            preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
            $total_length = strlen($ending);
            $open_tags = array();
            $truncate = '';
            $doingtag=0;
            foreach ($lines as $line_matchings) {
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
                if (!empty($line_matchings[1])) {
                    // if it's an "empty element" with or without xhtml-conform closing slash (f.e. 
)
                    if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
                        // do nothing
                    // if tag is a closing tag (f.e. </b>)
                    } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
                        // delete tag from $open_tags list
                        $pos = array_search($tag_matchings[1], $open_tags);
                        $doingtag=0;
                        if ($pos !== false) {
                            unset($open_tags[$pos]);
                        }
                    // if tag is an opening tag (f.e. <b>)
                    } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
                        // add tag to the beginning of $open_tags list
                        array_unshift($open_tags, strtolower($tag_matchings[1]));
                        $doingtag=1;
                    }
                    // add html-tag to $truncate'd text
                    $truncate .= $line_matchings[1];
                }
                // calculate the length of the plain text part of the line; handle entities as one character
                $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
                if ($total_length+$content_length> $length) {
                    // the number of characters which are left
                    $left = $length - $total_length;
                    $entities_length = 0;
                    // search for html entities
                    if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
                        // calculate the real length of all entities in the legal range
                        foreach ($entities[0] as $entity) {
                            if ($entity[1]+1-$entities_length <= $left) {
                                $left--;
                                $entities_length += strlen($entity[0]);
                            } else {
                                // no more characters left
                                break;
                            }
                        }
                    }
                    $truncate .= substr($line_matchings[2], 0, $left+$entities_length);
                    // maximum lenght is reached, so get off the loop
                    break;
                } else {
                    $truncate .= $line_matchings[2];
                    $total_length += $content_length;
                }
                // if the maximum length is reached, get off the loop
                if($total_length>= $length) {
                    break;
                }
            }
        } else {
            if (strlen($text) <= $length) {
                return $text;
            } else {
                $truncate = substr($text, 0, $length - strlen($ending));
            }
        }
        // if the words shouldn't be cut in the middle...
        if (!$exact) {
            // ...search the last occurance of a space...
            if(!$doingtag) { $spacepos = strrpos($truncate, ' '); }
            else { $spacepos=strrpos($truncate,'>'); }
            if (isset($spacepos)) {
                // ...and cut the text in this position
                $truncate = substr($truncate, 0, $spacepos);
                if($doingtag){$truncate.=">";}
            }
        }
        // add the defined ending to the text
        $truncate .= $ending;
        if($considerHtml) {
            // close all unclosed html-tags
            foreach ($open_tags as $tag) {
                $truncate .= '</' . $tag . '>';
            }
        }
        return $truncate;
    }

требует небольшой доработки напильником.
avatar
но выглядит, собака, сложно.
avatar
в ЛС кат работает, как по мне, немного странно.
Текст <a href='google.com' >goooo<cut>oogle</a>

в посте будет выглядеть
как:
Текст <u>goooo</u>oogle
то есть, закрывающий тег появляется в другом месте.
Текст <a href='google.com' <cut> >goooooogle</a>
даст такой результат:
Текст <a href='google.com' >goooooogle
то есть, закрывающий тег пропадает.
avatar
очень оперативно = )
Спасибо.
avatar
Огромное Вам спасибо!
avatar
а можно сделать чтобы тег ставился автоматом
Если
Тег не присутствует, то
после N количество символов ставится тег
Или если тег есть
то не чего не ставится
avatar
ответ ниже. да, можно
avatar
Вот мой код специально для ЛС. Работает у меня в плагине. получает исходный код топика, возвращает обрезанный.
тут есть проверка на наличие ката и пару ссылок на конфиг, но что они значат, вроде понятно.

/*************************************************************
 	* Add cut tag
 	**************************************************************/
	protected function PokupalkaCutAdd($str) {
		$iLengthMax=Config::Get('pokupalka.goods.text.length_before_cut');
		$iTextLength=mb_strlen($str,'UTF-8');
		$cutpos;
# Это теги, между которыми КАТ ставить низзя.
		$aTagUnbreakable=array('video','code','a','blockquote');
		#exclude video link from counting position
		$sPrestripKey='/<?video>[^>]*<?\/video>/i';
		$sPrestripped=preg_replace($sPrestripKey,'',$str);	
		$sStripped=preg_replace ('/<[^>]*>/', '',$sPrestripped);
		#check stripped text length;
		if(strlen($sStripped)<=$iLengthMax){
			return $str;
		}
		#get current CUT position if exists
		$cutpos=mb_strpos(preg_replace('/<(?!cut)[^>]*>/','',$sPrestripped),'<cut>',0,"UTF-8");
		if($cutpos!==false && $cutpos<=$iLengthMax){	 
			return $str;
		}else{
		#remove CUT	
		$str=preg_replace('/<cut>/','',$str);
		$cutpos=0;#calculated CUT position
		$i=0;#char counter
		$countchar=0;#visible chars counter
		
		$bInTag=false;#if we are <inside of a tag>
		$bRecTag=false;#start recording tag name
		$bCount=true;#<don't>DO COUNT<don't>
		#current tag name
		$sCurrentTag='';
		#if we are waiting for tag closure
		$sWaitTag='';

		#moving thrugh text		
		while($countchar<=$iLengthMax && $i<$iTextLength){
			$current=mb_substr($str,$i,1,'UTF-8');
			#Find where the tag begins and start recording it
			if ($current=='<'){
				#set Cut position before tag;
				if($i!=0 && $sWaitTag==''){$cutpos=$i-1;}
				#if it's a second open tag then it's not a tag;
				if($bInTag){
				$bInTag=false;
				$bRecTag=false;
				$bCount=true;
				$countchar+=strlen($sCurrentTag)+2;
				}else{
				$sCurrentTag='';
				$bInTag=true;
				$bRecTag=true;
				$bCount=false;
				
				}
			}
			#close tag
			elseif($current=='>'){
			if ($bInTag){
			$bInTag=false;
			$bRecTag=false;
				}else{
					$countchar++;
					}
				if(in_array($sCurrentTag, $aTagUnbreakable)){
					$sWaitTag=$sWaitTag==''?$sCurrentTag:'';	
					}
				if($sWaitTag!='video' ){
					$bCount=true;
					}
			#Space character	
			}elseif($current==' '){
				if ($bCount){
					$countchar++;
				}
				if($bInTag && !$sCurrentTag==''){
					$bRecTag=false;
				}
				#stop recording tag if it's length is over 11 chars
				if($bRecTag && (strlen($sCurrentTag)>11)){
					$bRecTag=false;
					$bInTag=false;
					$bCount=true;
					$countchar+=strlen($sCurrentTag)+2;
				}
				#if we are not in tag set cut position at this space symbol place
				if(!$bInTag && $sWaitTag==''){
					$cutpos=$i;
				}
			}else{
				if($bCount){	
				$countchar++;
				}
				#stop recording tag if it's length is over 11 chars
				if($bRecTag&&(strlen($sCurrentTag)>11)){
					$bRecTag=false;
					$bInTag=false;
					$bCount=true;
					$countchar+=strlen($sCurrentTag)+2;
				}
				#record current	character as one of the tag
				if($bRecTag && $current!='<' && $current!='/' && $current!=' '){$sCurrentTag.=$current;}
			}
		#char position enumerator
		$i++;	
		}
		#insert a cut tag;
		$str = mb_substr($str, 0, $cutpos,'UTF-8').'<cut>'.mb_substr($str, $cutpos,$iTextLength,'UTF-8');
		}
		return $str;
		#END OF CUT ADD FUNCTION
	}
avatar
Упаковал в плагин:

livestreet.ru/blog/7229.html
Только зарегистрированные и авторизованные пользователи могут оставлять комментарии.