将大字符串拆分为数组,但拆分点不能破坏标记

时间:2010-07-20 21:17:26

标签: php string-split

我编写了一个脚本,向Google发送大量文本进行翻译,但有时文本(html源代码)最终会在html标记的中间分割,而Google会错误地返回代码。

我已经知道如何将字符串拆分成数组,但有没有更好的方法来确保输出字符串不超过5000个字符并且不会在标记上拆分?

更新:感谢回答,这是我最终在我的项目中使用的代码,它运行良好

function handleTextHtmlSplit($text, $maxSize) {
    //our collection array
    $niceHtml[] = '';

    // Splits on tags, but also includes each tag as an item in the result
    $pieces = preg_split('/(<[^>]*>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);

    //the current position of the index
    $currentPiece = 0;

    //start assembling a group until it gets to max size

    foreach ($pieces as $piece) {
        //make sure string length of this piece will not exceed max size when inserted
        if (strlen($niceHtml[$currentPiece] . $piece) > $maxSize) {
            //advance current piece
            //will put overflow into next group
            $currentPiece += 1;
            //create empty string as value for next piece in the index
            $niceHtml[$currentPiece] = '';
        }
        //insert piece into our master array
        $niceHtml[$currentPiece] .= $piece;
    }

    //return array of nicely handled html
    return $niceHtml;
}

3 个答案:

答案 0 :(得分:3)

注意:没有机会测试这个(因此可能会有一两个小错误),但它应该给你一个想法:

function get_groups_of_5000_or_less($input_string) {

    // Splits on tags, but also includes each tag as an item in the result
    $pieces = preg_split('/(<[^>]*>)/', $input_string,
        -1, PREG_SPLIT_DELIM_CAPTURE);

    $groups[] = '';
    $current_group = 0;

    while ($cur_piece = array_shift($pieces)) {
        $piecelen = strlen($cur_piece);

        if(strlen($groups[$current_group]) + $piecelen > 5000) {
            // Adding the next piece whole would go over the limit,
            // figure out what to do.
            if($cur_piece[0] == '<') {
                // Tag goes over the limit, just put it into a new group
                $groups[++$current_group] = $cur_piece;
            } else {
                // Non-tag goes over the limit, split it and put the
                // remainder back on the list of un-grabbed pieces
                $grab_amount = 5000 - $strlen($groups[$current_group];
                $groups[$current_group] .= substr($cur_piece, 0, $grab_amount);
                $groups[++$current_group] = '';
                array_unshift($pieces, substr($cur_piece, $grab_amount));
            }
        } else {
            // Adding this piece doesn't go over the limit, so just add it
            $groups[$current_group] .= $cur_piece;
        }
    }
    return $groups;
}

另请注意,这可以在常规字词的中间分割 - 如果您不想这样做,请修改以// Non-tag goes over the limit开头的部分,为$grab_amount选择更好的值。我没有费心去编码,因为这只是一个如何解决分裂标签的例子,而不是插入式解决方案。

答案 1 :(得分:0)

为什么不在将字符串中的html标记发送到谷歌之前将其删除。 PHP有一个strip_tags()函数可以为你做这个。

答案 2 :(得分:0)

具有良好正则表达式的

preg_split会为你做到。