jQuery を用いて和文中の欧文に対してスペースを付与していましたが、 何とか php での処理が可能になったので紹介します。
和欧間スペースの仕組みは単純なもので、 文中の欧文を正規表現で検索し、 該当した箇所を <span class = "thx_wao"> で囲んでいるだけです。
が、 そもそも html のタグが欧文なので、 まずは html を 「タグ」 と 「それ以外」 に分割し、 「それ以外」 の部分に対してのみ、 正規表現での検索・置換を行う必要があります。
html をタグとそれ以外に分割
php
//html をテキストとタグに分解
function html_split_text_tag( $html ) {
//alt 内の 「>」 を文字参照に
if ( preg_match_all( '{alt="[^\"]*>}uis', $html, $match ) ) {
foreach ( $match as $value ) {
$alt_amp = preg_replace( '{(>)}is', '>', $value );
$html = str_replace( $value, $alt_amp, $html );
}
}
//html をテキストとタグに分解・ペアリング
$tag_match = '{(<.*?>)}uis';
$pairing = array_chunk(
preg_split(
$tag_match,
$html,
-1,
PREG_SPLIT_DELIM_CAPTURE
),
2
);
// ペア補充 (notice 対策)
$count = count( $pairing );
$pairing[ $count - 1 ] = array( ' ', ' ' );
return $pairing;
}//html_split_text_tag( $html )
注意点としては、 <img alt="<rt> タグが原因 "...> といった記述があった場合、 正規表現では 「<img alt="<rt>」 までをタグとして認識してしまうため、 予め alt 内の 「>」 を 「>」 に変換する必要があります。
サンプルが少ないため、 alt 以外にも 「>」 が出現するケースがあるかと思いますので、 その都度 「>」 変換のルール追加が必要ですね。
「それ以外」 の部分を検索・置換
php
// 和欧間スペース
function wao_space( $the_content ) {
//html をテキストとタグに分解
$pairing = html_split_text_tag( $the_content );
// ペアリングを span しながら結合
$the_content = '';
$ltn_match = '{[ !-;=-~\p{Ll}]+}uis';
$ltn_replece = '<span class = "thx_wao">$0</span>';
foreach ( $pairing as $value ) {
$str = trim( $value[0] );
$tag = $value[1];
if ( '</style>' === $tag ) {
$the_content .= $str . $tag;
} else {
$the_content
.= preg_replace(
$ltn_match,
$ltn_replece,
$str
) . $tag;
}
}
return $the_content;
}//wao_space($the_content)
add_filter( 'the_content', 'wao_space', 21000 );
the_content 内に <style> タグが出現したケースがありましたので、 その際は置換を行わない様にしてあります。
まとめ
html を 「タグ」 と 「それ以外」 に分割
これが非常に難儀でした。
こちらのページをを参考にさせて頂き、 上手く処理できた時といったら何かヘンな声が出るほど嬉しかったです w
この処理を実装できた恩恵は大きく、 今後の文字組版カスタマイズの基幹となります。
本来であれば、 「ぶら下がり」・「役物詰め」 の記事を投稿する予定なのでしたが、 それらの記事に於いてもこの処理を利用しているので、 事前に紹介させて頂きました。
コメント