: ( ) | three times in a row.
*
* @package Tidelist
*/
namespace Tidelist\Build;
/**
* Text rules.
*/
final class TextRules {
const PUNCTUATION = '!?.,\-=+#%&@*_><:()|';
/**
* Converts shop HTML into plain text: lists become bullet lines, block tags become line breaks,
* "show more / show less" buttons are dropped, entities are decoded.
*
* @param string $html HTML.
*/
public static function html_to_text( string $html ): string {
// Drop toggle buttons such as "Виж още / Виж по-малко" and any scripts/styles.
$html = (string) preg_replace( '#<(script|style)\b[^>]*>.*?\1>#is', '', $html );
$html = (string) preg_replace( '#
]*class="[^"]*(button|toggle)[^"]*"[^>]*>.*?
#is', '', $html );
$html = (string) preg_replace( '#]*>#i', "\n• ", $html );
$html = (string) preg_replace( '#
|(p|div|h[1-6]|li|ul|ol|tr)>#i', "\n", $html );
$text = html_entity_decode( strip_tags( $html ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags -- pure class; scripts and styles are removed above.
$text = str_replace( "\xC2\xA0", ' ', $text );
$lines = array();
foreach ( preg_split( '/\R/u', $text ) as $line ) {
$line = trim( (string) preg_replace( '/[ \t]+/u', ' ', $line ) );
if ( '' === $line || '•' === $line ) {
continue; // Empty line, or the bullet of a nested list wrapper.
}
$lines[] = $line;
}
return implode( "\n", $lines );
}
/**
* Removes e-mail addresses, web addresses and phone-like numbers (7+ digits, with optional separators).
*
* @param string $text Text.
*/
public static function remove_contacts( string $text ): string {
$text = (string) preg_replace( '/[^\s@]+@[^\s@]+\.[a-z]{2,}/iu', '', $text );
$text = (string) preg_replace( '#(https?://|www\.)\S+#iu', '', $text );
$text = (string) preg_replace( '/\b[a-z0-9-]+\.(bg|com|net|org|eu|info)\b/iu', '', $text );
$text = (string) preg_replace( '/(? $max * 0.7 ) {
return rtrim( mb_substr( $cut, 0, $sentence + 1, 'UTF-8' ) );
}
$space = mb_strrpos( $cut, ' ', 0, 'UTF-8' );
return rtrim( false !== $space ? mb_substr( $cut, 0, $space, 'UTF-8' ) : $cut, ' ,;–-' ) . '…';
}
/**
* Applies every safe automatic fix.
*
* @param string $text Text.
* @param bool $strip_contacts Whether e-mail addresses, web addresses and phone numbers are removed.
*/
public static function clean( string $text, bool $strip_contacts = true ): string {
return self::fix_caps( self::collapse_punctuation( $strip_contacts ? self::remove_contacts( $text ) : $text ) );
}
/**
* Character length (multibyte).
*
* @param string $text Text.
*/
public static function length( string $text ): int {
return mb_strlen( $text, 'UTF-8' );
}
}