在HTML元素中随机播放文本

时间:2015-02-19 14:10:20

标签: php html-parsing shuffle

我正在尝试使用PHP-shuffle函数和Simple HTML Parser来随机播放文章。

例如,这是我的内容:

<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>

然而,使用Simple HTML DOM解析器,我发现很难防止图像被扭伤,因为它们有时被放在段落中。

这是我目前的脚本。我觉得它很复杂,有时候输出的结果不正确。

希望有人可以帮助我。

    $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;

1 个答案:

答案 0 :(得分:-1)

使用:

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