Skip to content

Instantly share code, notes, and snippets.

@josf
Created May 19, 2015 12:01
Show Gist options
  • Select an option

  • Save josf/5b30d063264fb8e3d48a to your computer and use it in GitHub Desktop.

Select an option

Save josf/5b30d063264fb8e3d48a to your computer and use it in GitHub Desktop.
<?php
/**
* @param DOMNode to be truncated
* @return DOMNode
*
* NB: le DOMNode retourné doit être préalablement importé dans le
* Document où il va résider.
*/
function truncateNode (DOMNode $nd, $length = 100) {
if (strlen($nd->textContent) <= $length) {
return $nd;
}
$tmpDoc = new DOMDocument();
$impNode = $tmpDoc->importNode($nd, true); // deep
$tmpDoc->appendChild($impNode);
/* pour éviter d'avoir la decl xml */
$html = $tmpDoc->saveXML($tmpDoc->documentElement);
$truncated = cuttext($html, $length, true); // true is for dots opt
$doc = new DOMDocument();
$doc->loadXML($truncated);
return $doc->documentElement;
}
function margenote ($texte, $notes) {
/* construire les notes */
$notes_paragraphes = preg_split('/(?=<p\s+class="notesbaspage")/', $notes);
/* because of look ahead matches, there is an empty string at the
* beginning that we have to shift away */
array_shift($notes_paragraphes);
$note_nodes = array();
foreach ($notes_paragraphes as $n) {
$ndoc = new DOMDocument();
$ndoc->loadXML($n);
$aNode = $ndoc->getElementsByTagName("a")->item(0);
if ($aNode) { // pour les paragraphes sans <a>...?
$note_nodes[$aNode->getAttribute("id")] = array(
'href' => $aNode->getAttribute("href"),
'note_texte_elem' =>
truncateNode($ndoc->getElementsByTagName("p")->item(0), 80)
);
}
}
/* le texte */
$tDoc = new DOMDocument();
$tDoc->loadXML('<body>' . $texte . '</body>');
/* prenant exemple sur paranumber() */
$tDom = new DOMXPath($tDoc);
$tDom->preserveWhiteSpace = true;
$tDom->formatOutput = false;
foreach ($tDom->query(
"/body/*[sup[a[@class='footnotecall']]]|/body/*[a[@class='footnotecall']]"
) as $p) {
$ul = $tDoc->createElement("ul");
$ul = $p->parentNode->insertBefore($ul, $p);
$ul->setAttribute("class", "notes-marge");
// boucle sur les <a> dans le paragraphe. $p devient le context node
foreach($tDom->query("descendant::a[@class='footnotecall']", $p) as $aFn) {
$li = $tDoc->createElement("li");
$ul->appendChild($li);
$appelHref = substr($aFn->getAttribute("href"), 1); // supprimer '#'
// retrouver la note correspondante,
if (array_key_exists($appelHref, $note_nodes)) {
$noteNode = $tDoc->importNode(
$note_nodes[$appelHref]['note_texte_elem'],
TRUE // deep copy
);
$li->appendChild($noteNode);
$id = $noteNode->firstChild->getAttribute("id");
$noteNode->firstChild->removeAttribute("id");
$noteNode->firstChild->setAttribute("href", "#" . $id);
}
}
}
// comme paranumber() encore
$retTexte = '';
foreach ($tDom->query('/body/*') as $elem) {
$retTexte .= $tDoc->saveXML($elem, LIBXML_NOEMPTYTAG);
}
return cleanHTML($retTexte);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment