<?php /* * Вставка мультимедиа объектов в тексты v.1.0 * * */ class mm_improver { private $aText; // массив текстов private $aRatioImg; // процент текстов с 1-ой картинкой, c 2-мя, c 3-мя private $tagImgPath; // путь к картинкам на сайте private $aTagImgCSS; // массив стилей для картинок private $pathImages; // дирректория с исх. картинками private $pathResImages; // дирректория со вставленными картинками // инициализация класса public function mm_improver( $aText = Array(), $aRatioImg = Array(60, 10, 5), $tagImgPath = '{IMG_PATH}', $aTagImgCSS = Array('class="img_left"', 'class="img_center"', 'class="img_right"'), $pathImages = 'input/images', $pathResImages = 'images' ) { $this->set_texts($aText); $this->aRatioImg = $aRatioImg; $this->tagImgPath = $tagImgPath; $this->aTagImgCSS = $aTagImgCSS; $this->pathImages = rtrim($pathImages, '/'); $this->pathResImages = rtrim($pathResImages, '/'); } // загрузить тексты для обработки public function set_texts($aText = Array()) { $this->aText = $aText; } // получить результат - массив текстов public function get_texts() { return $this->aText; } // вставить в текст строку private function insertSTRtoTEXT($text, $str) { $aLines = explode(".",$text); $partNum = floor(rand(0, 9) / 3); $partNum = ($partNum == 0) ? 1 : $partNum; $lineNum = rand(round(($partNum-1) * count($aLines)/3), round($partNum * count($aLines)/3 - 1)); $aLines[$lineNum] = "\r\n".$str."\r\n".$aLines[$lineNum]; $text = implode(".", $aLines); return $text; } /* * вставить в тексты картинки * $flMoveImages - переносить использованные картинки */ public function insert_images($flMoveImages = TRUE) { // подготавливаем массив $aSpaces, // в котором для каждой статьи указано кол-во картинок, которые нужно вставить $countText = count($this->aText); $aSpaces = Array(); foreach($this->aRatioImg as $numRatio => $ratio) { $tmpCount = round( $countText * $ratio / 100 ); $tmpArray = array_fill(0, $tmpCount, $numRatio + 1); $aSpaces = array_merge($aSpaces, $tmpArray); } $tmpArray = array_fill(0, $countText - count($aSpaces), 0); $aSpaces = array_merge($aSpaces, $tmpArray); shuffle($aSpaces); // ---------------------------------------- $aImages = glob($this->pathImages."/*.jpg"); shuffle($aImages); $curImgNum = 0; $maxImgNum = count($aImages) - 1; foreach($this->aText as $numText => $text) { for($i = 0; $i < $aSpaces[$numText]; $i++){ if($curImgNum > $maxImgNum) break; $tmpCSS = ''; $tmpCSS = $this->aTagImgCSS[rand(0, count($this->aTagImgCSS) - 1)]; $tmpImg = '<img' .($tmpCSS ? ' '.$tmpCSS.' ' : '') .'src="'.$this->tagImgPath.'/'.basename($aImages[$curImgNum]) .'" alt="" />'; $this->aText[$numText] = $this->insertSTRtoTEXT($text, $tmpImg); // перенос использованных картинок if($flMoveImages) rename($aImages[$curImgNum], $this->pathResImages.'/'.basename($aImages[$curImgNum])); $curImgNum++; } } return $this->aText; } /* * проверить наличие нужного кол-ва картинок * возвращает сколько картинок не хватает, 0 - картинок достаточно */ public function check_images_qty() { $aImages = glob($this->pathImages."/*.jpg"); $countImg = count($aImages); $countText = count($this->aText); $countSpace = 0; foreach($this->aRatioImg as $numRatio => $ratio) { $countSpace += ($numRatio + 1) * round($countText * $ratio / 100); } $res = ($countSpace - $countImg) > 0 ? ($countSpace - $countImg) : 0; return $res; } } ?>
<?php require_once('lib/mm_improver.php'); // формируем массив статей aText $text = file_get_contents('input/articles.txt'); preg_match_all('%<article>(.*?)</article>%ims', $text, $aArticles); $aText = $aArticles[1]; // вставляем картинки в тексты (картинки в дирректории input/images) $mm_improver = new mm_improver($aText, Array(60, 10, 5), 'input/images'); /* // проверка на достаточное кол-во картинок $imgNeed = $mm_improver->check_images_qty(); if( $imgNeed ) { echo 'Для расстановки не хватает '.$imgNeed.' картинок!'; exit; } */ $aText = $mm_improver->insert_images(FALSE); print_r($aText); ?>
Меню сайта
PHP класс: размещение картинки в тексте |