New split_text_into_spans function

This commit is contained in:
2025-09-04 16:01:06 +02:00
parent a48ea0de46
commit 7ad1eefe30
2 changed files with 57 additions and 2 deletions

View File

@@ -260,3 +260,58 @@ function load_more_posts_callback() {
wp_reset_postdata();
wp_die();
}
if (!function_exists('split_text_into_spans')) {
function split_text_into_spans($content, $wordClass = 'word', $charClass = 'char') {
if (empty($content)) return '';
$doc = new DOMDocument('1.0', 'UTF-8');
libxml_use_internal_errors(true);
$doc->loadHTML('<?xml encoding="utf-8" ?><div id="wrapper">'.$content.'</div>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
$xpath = new DOMXPath($doc);
$textNodes = $xpath->query("//div[@id='wrapper']//text()[not(ancestor::script or ancestor::style or ancestor::svg or ancestor::code or ancestor::pre or ancestor::iframe)]");
foreach ($textNodes as $node) {
$text = $node->nodeValue;
if (!preg_match('/\S/u', $text)) continue;
$fragment = $doc->createDocumentFragment();
$words = preg_split('/(\s+)/u', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($words as $word) {
if (trim($word) === '') {
$fragment->appendChild($doc->createTextNode($word));
continue;
}
$wordSpan = $doc->createElement('span');
$wordSpan->setAttribute('class', $wordClass);
$chars = preg_split('//u', $word, -1, PREG_SPLIT_NO_EMPTY);
foreach ($chars as $ch) {
$span = $doc->createElement('span');
$span->setAttribute('class', $charClass);
$span->appendChild($doc->createTextNode($ch));
$wordSpan->appendChild($span);
}
$fragment->appendChild($wordSpan);
}
$node->parentNode->replaceChild($fragment, $node);
}
$wrapper = $doc->getElementById('wrapper');
$html = '';
foreach ($wrapper->childNodes as $child) {
$html .= $doc->saveHTML($child);
}
return $html;
}
}

View File

@@ -54,8 +54,8 @@
<div class="container">
<div class="row">
<div class="col col-1" box-title="<?php echo $box2['mini_title']; ?>">
<div class="box-text">
<p><?php echo $box2['text']; ?></p>
<div class="box-text animate-text">
<?php echo split_text_into_spans($box2['text']); ?>
</div>
<a class="btn_4" href="<?php echo esc_url($box2['btn']['url']); ?>" target="<?php echo esc_attr($box2['btn']['target'] ?: '_self'); ?>">
<?php echo esc_html($box2['btn']['title']); ?>