Skip to content

Instantly share code, notes, and snippets.

@fl3pp
Created November 27, 2018 08:50
Show Gist options
  • Save fl3pp/cf44b3efd9166651229c4da60c9643dd to your computer and use it in GitHub Desktop.
Save fl3pp/cf44b3efd9166651229c4da60c9643dd to your computer and use it in GitHub Desktop.
Pico Anchors
<?php
# Create file 'PicoAnchors.php' in pico plugin folder and paste content
class PicoAnchors extends AbstractPicoPlugin {
public function onContentParsed(&$content) {
while ($this->getNextLink($content, $match)) {
$linkName = $match['name'][0];
$endingTagOffset = $match['endingtag'][1] + $this->lastOffset;
$matchContent = $match[0][0];
$link = "<a class=\"anchor\" href=\"#".$linkName."\">$linkName</a>";
$this->lastOffset += $match[0][1] + strlen($matchContent);
$content = substr_replace($content, $link, $endingTagOffset, 0);
}
}
private const REGEX = '/\<(.{1,5}).*id="(?<name>\S+)".*(?<endingtag>\<\/\1\>)/';
private $lastOffset = 0;
private function getNextLink($text, &$outMatch) {
$outMatch = null;
if (!preg_match($this::REGEX, substr($text, $this->lastOffset), $match, PREG_OFFSET_CAPTURE)) {
return false;
}
$outMatch = $match;
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment