From 75685f37379fae5067d405805bdcaf26b6d23387 Mon Sep 17 00:00:00 2001 From: yggverse Date: Fri, 5 Apr 2024 07:03:47 +0300 Subject: [PATCH] implement skipTags method --- README.md | 19 ++++++++++ src/Gemtext/Body.php | 85 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+) diff --git a/README.md b/README.md index 699c976..123e565 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,25 @@ var_dump( ); ``` +#### Body::skipTags + +Strip gemini tags from Gemini document + +``` +var_dump( + $body->skipTags() // strip all tags +); + +var_dump( + $body->skipTags( + [ // 1- and 2- level headers only + "##", + "###" + ] + ) +); +``` + ### Link Inline links parser. diff --git a/src/Gemtext/Body.php b/src/Gemtext/Body.php index a9d8209..5e18fd0 100644 --- a/src/Gemtext/Body.php +++ b/src/Gemtext/Body.php @@ -105,4 +105,89 @@ class Body return $matches; } + + public function skipTags(array $tags = []): string + { + $lines = []; + + foreach ($this->_lines as $line) + { + $line = trim( + $line + ); + + if ($tags) + { + foreach ($tags as $tag) + { + if(!in_array($tag, ['#', '##', '###', '=>', '*', '```'])) + { + continue; + } + + switch (true) + { + case str_starts_with($line, '#'): + + $line = preg_replace( + sprintf( + '/^%s([^#]+)/ui', + $tag + ), + '$1', + $line + ); + + break; + + case str_starts_with($line, '*'): + + $line = preg_replace( + '/^\*(.*)/ui', + '$1', + $line + ); + + break; + + default: + + $line = preg_replace( + sprintf( + '/^%s(.*)/ui', + $tag + ), + '$1', + $line + ); + } + } + } + + else + { + $line = preg_replace( + [ + '/^#([^#]+)/ui', + '/^##([^#]+)/ui', + '/^###([^#]+)/ui', + '/^=>(.*)/ui', + '/^\*(.*)/ui', + '/^```(.*)/ui', + ], + '$1', + $line + ); + } + + $lines[] = trim( + $line + ); + } + + return implode( + PHP_EOL, + $lines + ); + } } \ No newline at end of file