もう一度、正規表現で立ち往生しています。より高度な使用法を学ぶための良い資料はどこにもありません。
[image width="740" height="249" parameters=""]51lca7dn56.jpg[/image]
に一致さ せようとしてい$cache->image_tag("$4", $1, $2, "$3")
ます。
すべての[image]パラメータが存在する場合はすべてうまく機能しますが、何かが欠落している場合でも、一致させる必要があります。たとえば、[image width="740"]51lca7dn56.jpg[/image]
。
現在のコードは次のとおりです。
$text = preg_replace('#\[image width=\"(.*?)\" height=\"(.*?)\" parameters=\"(.*?)\"\](.*?)\[/image\]#e', '$cache->image_tag("$4", $1, $2, "$3")', $text);
いつも行き詰まっているのは正規表現だけなので、誰かが良いリソースを紹介してくれれば、この種の問題を自分で管理できれば幸いです。
私がやろうとしている私のダミーバージョンはこれです:
// match only [image]
$text = preg_replace('#\[image\](.*?)\[/image\]#si', '$cache->image_tag("$1", 0, 0, "")', $text);
// match only width
$text = preg_replace('#\[image width=\"(.*?)\"\](.*?)\[/image\]#si', '$cache->image_tag("$2", $1, 0, "")', $text);
// match only width and height
$text = preg_replace('#\[image width=\"(.*?)\" height=\"(.*?)\"\](.*?)\[/image\]#si', '$cache->image_tag("$3", $1, $2, "")', $text);
// match only all
$text = preg_replace('#\[image width=\"(.*?)\" height=\"(.*?)\" parameters=\"(.*?)\"\](.*?)\[/image\]#si', '$cache->image_tag("$4", $1, $2, $3)', $text);
(このコードは実際には期待どおりに機能しませんが、私のポイントをよりよく理解できます。)基本的にこの恐ろしい混乱をすべて1つのRE呼び出しにまとめたいと思います。
Ωmegaの答えに基づいてテストされ、機能する最終的なコード:
// Match: [image width="740" height="249" parameters="bw"]51lca7dn56.jpg[/image]
$text = preg_replace('#\[image\b(?=(?:[^\]]*\bwidth="(\d+)"|))(?=(?:[^\]]*\bheight="(\d+)"|))(?=(?:[^\]]*\bparameters="([^"]+)"|))[^\]]*\]([^\[]*)\[\/image\]#si', '$cache->image_tag("$4", $1, $2, "$3")', $text); // the end is #si, so it would be eaiser to debug, in reality its #e
ただし、幅または高さがない場合は、NULLではなく空が返されます。だから私はドローのアイデアを採用しましたpreg_replace_callback()
:
$text = preg_replace_callback('#\[image\b(?=(?:[^\]]*\bwidth="(\d+)"|))(?=(?:[^\]]*\bheight="(\d+)"|))(?=(?:[^\]]*\bparameters="([^"]+)"|))[^\]]*\]([^\[]*)\[\/image\]#', create_function(
'$matches',
'global $cache; return $cache->image_tag($matches[4], ($matches[1] ? $matches[1] : 0), ($matches[2] ? $matches[2] : 0), $matches[3]);'), $text);