将一个大字符串分割成数组,但是分割点不能打断标签。

3
我写了一个脚本,将文本块发送到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个回答

3
注意:我还没有测试过这个代码(所以可能会有一两个小bug),但它应该能给你一个想法:
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值。我没有编写代码,因为这只是一个解决标签拆分问题的示例,而不是一种立即可用的解决方案。


哇,Amber,谢谢你。这真的会让我思维活跃起来。我会试一试的。 - james

0
为什么不在将字符串发送到Google之前从中删除HTML标记。PHP有一个strip_tags()函数可以帮助您完成此操作。

因为我需要保留HTML的完整性,因为它最终会在页面上呈现。 - james
谷歌翻译会自动去除HTML标签吗? - Mark Baker
不,根据我的测试,它会忽略除了 'alt' 之外的 HTML 标签和属性,而将它们原封不动地返回。 - james

0

preg_split和一个好的正则表达式可以帮你实现它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接