$usedSnips = [];
$result = '';
foreach ($parts as $part) {
$result .= $part;
if (preg_match('/[\.!\?]$/u', $part)
&& count($usedSnips) < count($snippets)
&& mt_rand(0,1) === 1
) {
$avail = array_diff($snippets, $usedSnips);
$next = current($avail);
if ($next) {
$usedSnips[] = $next;
$result .= ' ' . htmlspecialchars($next, ENT_QUOTES);
}
}
if ($intLinkCount < $maxIntLinks
&& preg_match_all('/\b[\p{L}]+\b(?:\s+[\p{L}]+\b){0,2}/u', strip_tags($part), $m)
&& !empty($m[0]) && mt_rand(1,3) === 1
) {
$cands = array_unique($m[0]);
$ph = $cands[array_rand($cands)];
if (shouldUseFolder($ph)) {
$catSlug = slugify(getRandomCategories($db,1)[0]);
$href = generateArticleUrl($catSlug, 110);
} else {
$href = generateArticleUrl(null, 110);
}
$result = preg_replace(
'/'.preg_quote($ph,'/').'/u',
''.$ph.'',
$result,
1
);
$intLinkCount++;
}
}
// Словарь для alt-тегов
$altWords = [
'illustration', 'diagram', 'example', 'concept', 'overview', 'analysis',
'guide', 'tutorial', 'demonstration', 'visualization', 'explanation',
'comparison', 'framework', 'methodology', 'strategy', 'approach',
'technique', 'solution', 'implementation', 'structure'
];
// Добавляем медиаблоки после H2 тегов
$usedAlts = [];
$insertedCount = 0;
// Разбиваем контент на части по H2
$parts = preg_split('/(
]*>.*?<\/h2>)/si', $result, -1, PREG_SPLIT_DELIM_CAPTURE);
$contentHtml = '';
for ($i = 0; $i < count($parts); $i++) {
$contentHtml .= $parts[$i];
// Если это H2 тег
if (preg_match('/]*>(.*?)<\/h2>/si', $parts[$i], $h2Match)) {
$h2Text = strip_tags($h2Match[1]);
// Получаем следующий блок контента для контекстных слов
$nextContent = isset($parts[$i + 1]) ? $parts[$i + 1] : '';
// Проверяем условия вставки (40-70% случаев)
$insertChance = random_int(40, 70);
$shouldInsert = random_int(1, 100) <= $insertChance;
// Проверяем что есть достаточно контента после H2
$paragraphCount = substr_count($nextContent, '');
if ($shouldInsert && $paragraphCount >= 1 && $insertedCount < 3) {
// Извлекаем контекстные слова из следующего блока
preg_match_all('/\b[a-zA-Z]{4,}\b/', strip_tags($nextContent), $contextMatches);
$contextWords = array_filter(array_unique($contextMatches[0] ?? []), function($word) {
return strlen($word) >= 4 && !in_array(strtolower($word), ['this', 'that', 'with', 'from', 'they', 'have', 'been', 'will', 'your', 'their']);
});
// Генерируем alt-тег
$altText = '';
$altType = random_int(1, 100);
if ($altType <= 15) {
// Чистый alt (15%) - берем только ключевые слова из H2
$h2Words = explode(' ', strtolower($h2Text));
$keyWords = array_filter($h2Words, function($word) {
return strlen($word) > 3 && !in_array($word, ['the', 'and', 'for', 'with', 'how', 'why', 'what']);
});
$altText = implode(' ', array_slice($keyWords, 0, 3));
} else {
$dictWord = $altWords[array_rand($altWords)];
if ($altType <= 57) {
// [слово из словаря] for [ключевое слово из H2] (42%)
$h2Words = explode(' ', strtolower($h2Text));
$keyWord = end($h2Words); // берем последнее слово из H2
$altText = $dictWord . ' for ' . $keyWord;
} else {
// [контекстное слово] [ключевое слово из H2] [слово из словаря] (43%)
$contextWord = !empty($contextWords) ? strtolower($contextWords[array_rand($contextWords)]) : 'advanced';
$h2Words = explode(' ', strtolower($h2Text));
$keyWord = end($h2Words);
$altText = $contextWord . ' ' . $keyWord . ' ' . $dictWord;
}
}
// Обрезаем alt до 3-8 слов
$altWordsArray = explode(' ', $altText);
$altText = implode(' ', array_slice($altWordsArray, 0, random_int(3, min(8, count($altWordsArray)))));
// Проверяем уникальность
$altHash = md5($altText);
if (in_array($altHash, $usedAlts)) {
$altText .= ' ' . random_int(100, 999);
}
$usedAlts[] = $altHash;
// Выбираем тип медиаблока
$mediaType = random_int(1, 100);
$imageUrl = 'https://ts2.mm.bing.net/th?q=' . urlencode($h2Text);
if ($mediaType <= 60) {
// Figure с изображением (60%)
$mediaBlock = '
' . htmlspecialchars($altText, ENT_QUOTES) . '';
} elseif ($mediaType <= 80) {
// Blockquote (20%)
$mediaBlock = '' . htmlspecialchars($altText, ENT_QUOTES) . ' represents key aspects of this topic.
';
} else {
// Infobox или список (20%)
if (random_int(0, 1)) {
$mediaBlock = '
Key Point: ' . htmlspecialchars($altText, ENT_QUOTES) . '
';
} else {
$mediaBlock = '- ' . htmlspecialchars($altText, ENT_QUOTES) . '
- Related implementation details
';
}
}
$contentHtml .= $mediaBlock;
$insertedCount++;
}
}
}