You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
2.1 KiB
64 lines
2.1 KiB
<?php |
|
|
|
// Sécurité |
|
if (!defined('_ECRIRE_INC_VERSION')) {return;} |
|
|
|
/** |
|
* Ajuster le niveau des intertitres dans un texte |
|
* h2->h3 |
|
* h3->h4 |
|
* etc. |
|
* @param string $texte |
|
* @param str|int=1 $decalage_ou_niveau : |
|
* - si int : 1 pour augmenter d'un niveau, -1 pour baisser d'un niveau |
|
* - si str de la forme `hx`, alors fait commencer les titres à hx, et descend ensuite (`hx+1`, `hx+2` etc.) |
|
* @param string ('blockquote') $echappe, ne pas appliquer le traitement au sein de certaines balises HTML. Exemple `blockquote|article|aside|nav|section` |
|
**/ |
|
function ajuster_intertitres($texte, $decalage_ou_niveau = 1, $echappe = 'blockquote') { |
|
$decalage = intval($decalage_ou_niveau); |
|
if (!$decalage) { |
|
if (substr($decalage_ou_niveau, 0, 1) === 'h' and $niveau = intval(substr($decalage_ou_niveau, 1, 1))) { |
|
preg_match_all('#<h([1-6])\b#', $texte, $matches); |
|
if (!$matches[1]) { |
|
return $texte; |
|
} |
|
$base_actuel = min($matches[1]); |
|
$decalage = $niveau - $base_actuel; |
|
} else { |
|
return $texte; |
|
} |
|
} |
|
|
|
// On echape |
|
if ($echappe) { |
|
$preg = ',<('.$echappe.')\b([^>]*)?>(.*)</\1>,UimsS'; |
|
$texte = echappe_html($texte, '', true, $preg); |
|
} |
|
|
|
$niveau_max_recherche = 6-$decalage; // h5+1 -> h6, mais h6+1 -> h6, car h7 n'existe pas |
|
// Si on décale vers le haut (+1), alors on commence par décaler les titres avec le plus grand chiffre, puis ceux avec le chiffres le plus bas (h5->h6, puis h4->h5, etc.) |
|
// Si on décale vers le bas (-1), alors c'est l'inverse (h2->h1, puis h3->h2. etc.) |
|
// Ceci pour éviter de décaler quelque chose qu'on a déjà décalé. |
|
// L'ordre de décalage est stocké dans $increment |
|
if ($decalage > 0) { |
|
$ancien_niveau = $niveau_max_recherche; |
|
$increment = -1; |
|
} elseif ($decalage === 0) { |
|
return $texte; |
|
} else { |
|
$ancien_niveau = 1; |
|
$increment = +1; |
|
} |
|
|
|
while ($ancien_niveau > 0 and $ancien_niveau <= $niveau_max_recherche){ |
|
$nouveau_niveau = $ancien_niveau+$decalage; |
|
if ($nouveau_niveau > 0) { |
|
$texte = preg_replace('/<(\/?)h'.$ancien_niveau.'\b/', '<$1h'.$nouveau_niveau, $texte); |
|
} |
|
$ancien_niveau = $ancien_niveau+$increment; |
|
} |
|
if ($echappe) { |
|
$texte = echappe_retour($texte); |
|
} |
|
return $texte; |
|
}
|
|
|