PHP -在x个单词后插入文本,但不在标签内

4urapxun  于 2023-06-04  发布在  PHP
关注(0)|答案(1)|浏览(137)

我有以下字符串:
Lorem ipsum <strong>dolor sit amet</strong>Aenean fermentum risus <strong><a href="https://google.com">id tortor.</a></strong> <strong>Suspendisse nisl.</strong> dictum at dui. Aenean id metus <strong><a href="https://google.com"> id velit</a> ullamcorper pulvinar</strong>. Neque porro quisquam es qui dolorem ipsum.
我需要在第10个单词后插入文本read more,但前提是它不在html标记内。为了更清楚,我需要计算单词(即使是标记内部的单词),找到第10个单词,如果是内部标记,则继续到外部标记的末尾,并在该位置插入read more
简单的explode by space显然不适用于这种情况。有人能帮忙吗?

z0qdvdin

z0qdvdin1#

当您运行此代码时,您可以看到给定示例文本的修改版本,在第10个单词后添加了“新文本”。

<?php
    function insertAfterTenWords($text, $insertion) {
        $words = preg_split('/\s+/', $text);
        $wordCount = count($words);
        $openTags = [];
        $newText = '';
        
        for ($i = 0; $i < $wordCount; $i++) {
            $word = $words[$i];
            
            if (strpos($word, '<') !== false) {
                $openTags[] = substr($word, strpos($word, '<'));
                $newText .= $word . ' ';
            } else if (strpos($word, '>') !== false) {
                $lastTag = array_pop($openTags);
                $newText .= $word . ' ';
                
                while ($lastTag != substr($word, strpos($word, '<'))) {
                    $word = $words[++$i];
                    $newText .= $word . ' ';
                }
            } else {
                $newText .= $word . ' ';
            }
            
            if ($i == 9 && count($openTags) == 0) {
                $newText .= $insertion . ' ';
            }
        }
        
        while (count($openTags) > 0) {
            $newText .= array_pop($openTags);
        }
        
        return trim($newText);
    }
    
    $text = 'Lorem ipsum <strong>dolor sit amet</strong>Aenean fermentum risus <strong><a href="https://google.com">id tortor.</a></strong> <strong>Suspendisse nisl.</strong> dictum at dui. Aenean id metus <strong><a href="https://google.com"> id velit</a>  ullamcorper pulvinar</strong>. Neque porro quisquam es qui dolorem ipsum.';
    $insertion = '<a href="#">new text</a>';
    
    echo insertAfterTenWords($text, $insertion);
?>

相关问题