テキストのチャンクを 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;
}