状況は次のような結果になる文字列です。
<p>This is some text and here is a <strong>bold text then the post stop here....</p>
この関数はテキストのティーザー (要約) を返すため、特定の単語の後に停止します。この場合、タグは閉じられていません。ただし、文字列全体が段落で囲まれています。
上記の結果/出力を次のように変換することは可能ですか?
<p>This is some text and here is a <strong>bold text then the post stop here....</strong></p>
どこから始めればいいのかわかりません。問題は、正規表現を実行する関数を Web で見つけたのですが、文字列の後に終了タグが置かれてしまうことです。そのため、段落タグ内のすべての開始/終了タグが必要なため、検証されません。私が見つけた関数はこれを実行しますが、これも間違っています。
<p>This is some text and here is a <strong>bold text then the post stop here....</p></strong>
タグは太字、斜体、何でもいいことを知りたいです。そのため、関数を追加して関数内で手動で閉じることはできません。これを実現できるパターンはありますか?
ベストアンサー1
以下は私が以前使用した関数ですが、非常にうまく機能します。
function closetags($html) {
preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
$openedtags = $result[1];
preg_match_all('#</([a-z]+)>#iU', $html, $result);
$closedtags = $result[1];
$len_opened = count($openedtags);
if (count($closedtags) == $len_opened) {
return $html;
}
$openedtags = array_reverse($openedtags);
for ($i=0; $i < $len_opened; $i++) {
if (!in_array($openedtags[$i], $closedtags)) {
$html .= '</'.$openedtags[$i].'>';
} else {
unset($closedtags[array_search($openedtags[$i], $closedtags)]);
}
}
return $html;
}
ただし、個人的には、正規表現ではなく、Tidy などのライブラリを使用します。これは次のようになります。
$str = '<p>This is some text and here is a <strong>bold text then the post stop here....</p>';
$tidy = new Tidy();
$clean = $tidy->repairString($str, array(
'output-xml' => true,
'input-xml' => true
));
echo $clean;