打乱HTML元素中的文本


Shuffle text inside HTML elements

我正在尝试用PHP shuffle函数和Simple HTML Parser对文章进行shuffle。

例如,这是我的内容:

<p>This is my article.</p>
<h2>This is a subheading</h2>
<p>This is an paragraph with an image inside it <img src="http://image.jpg">
</p>

输出应该是这样的:

<p>article is This my .</p>
<h2>This subheading is a</h2>
<p>is an  with an image paragraph inside This it <img src="http://image.jpg"></p>

然而,使用SimpleHTMLDOM解析器,我发现很难防止图像被去除,因为它们有时被放在段落中。

这是我目前的剧本。我觉得这太复杂了,有时不会输出正确的结果。

希望有人能帮我。

    $tags           = 'p, ul, ol, blockquote, h1, h2, h3, h4, h5, h6, h7';
    $html           = str_get_html( $html );
    /**
     * Loop through HTML and set output 
     */
    foreach( $html->find( $tags ) as $article ) {
        $element    = $article->outertext;
        $array      = $article;
        $tag        = $article->tag;
        $innerHTML  = '';
        // Nested paragraphs
        foreach ( $array->find('p') as $el ){
            $word_array = preg_replace( "#['s]+#", " ", $el->innertext );
            $words      = explode( " ", $word_array );
            $w          = '';
            shuffle( $words );
            foreach ( $words as $word ){
                $w .= $word . ' ';
            }
            $innerHTML .= $el->innertext = $w;
        }
        // List items
        foreach ( $array->find('li') as $el ){
            $word_array = preg_replace( "#['s]+#", " ", $el->innertext );
            $words      = explode( " ", $word_array );
            $w          = '';
            shuffle( $words );
            foreach ( $words as $word ){
                $w .= $word . ' ';
            }
            $innerHTML .= $el->innertext = '<li>' . $w . '</li>';
        }
        // Images
        foreach ( $array->find('img') as $el ) {
            // Blur image
            $src      = stripslashes( str_replace( '"', '', $el->src ) );
            $new_src  = $this->create_blur_image( $src );
            // Replace url with base64 encode
            $src        = $el->src = $new_src;
            $innerHTML .= $el->outertext;
        }
        // Output
        if ( $innerHTML ){
            $element = $article->innertext = $innerHTML;
        } else {
            $word_array = preg_replace( "#['s]+#", " ", $article->innertext );
            $words      = explode( " ", $word_array );
            $w          = '';
            shuffle( $words );
            foreach ( $words as $word ){
                $w .= $word . ' ';
            }
            $element = $article->innertext = $w;
        }
        $output .= $article->outertext;
    }
    $html = $output;
    return $html;

使用:

function shuffle($text){
 $text_array = array_shuffle(explode(" ",$text)); 
 $text_string = implode($text_array," ");
 return $text_string;
}