mediawiki-extensions-Descri.../includes/SimpleDescriptionProvider.php
xtex 055927a901 Remove style tags in description
Some pages' description may include CSS code rendered by [[Extension:TemplateStyles]].

Change-Id: I352ac2338eb5977305308546523ec6c55f7cb599
2024-02-14 07:16:19 +00:00

41 lines
1.1 KiB
PHP

<?php
namespace MediaWiki\Extension\Description2;
class SimpleDescriptionProvider implements DescriptionProvider {
/**
* Extracts description from the HTML representation of a page.
*
* The algorithm:
* 1. Removes all <style> and <table> elements and their contents.
* 2. Selects all <p> elements.
* 3. Iterates over those paragraphs, strips out all HTML tags and trims white-space around.
* 4. Then the first non-empty paragraph is picked as the result.
*
* @param string $text
* @return string
*/
public function derive( string $text ): ?string {
$myText = $text;
$stripTags = [ 'style', 'table' ];
foreach ( $stripTags as $tag ) {
$pattern = "%<$tag\b[^>]*+>(?:(?R)|[^<]*+(?:(?!</?$tag\b)<[^<]*+)*+)*+</$tag>%i";
$myText = preg_replace( $pattern, '', $myText );
}
$paragraphs = [];
if ( preg_match_all( '#<p>.*?</p>#is', $myText, $paragraphs ) ) {
foreach ( $paragraphs[0] as $paragraph ) {
$paragraph = trim( strip_tags( $paragraph ) );
if ( !$paragraph ) {
continue;
}
return $paragraph;
}
}
return null;
}
}