PHP::正規表現::時間かかりすぎ

tableはどうすればいいのか見当がつかなくなってきたのでpに変更。

ひょいひょい変わる辺り忍耐力が減ってきた気がする。

正規表現であれこれするだけで8hくらいPCに向かってカタカタやっている。

それなのに遅々として進まないのが腹立たしい。

さて、今回は

//$text
<p style="text-align: center; margin-left: 40px;">...</p>
<p style="margin-left: 40px; text-align: center;">...</p>
<p style="text-align: right;">...</p>
<p style="margin-left: 40px;">...</p>
<p>...</p>

これを

\begin{center}
\begin{indentation}{40px}
...
\end{indentation}
\end{center}



\begin{indentation}{40px}
\begin{center}
...
\end{center}
\end{indentation}


\begin{flushright}
...
\end{flushright}


\begin{indentation}{40px}
...
\end{indentation}


...

としたい。

さてどうしたものか。

とりあえず順に考えてみた。(この時点で間違っているとしたらオワタ)

  1. pタグの属性があるのかどうかを判定
  2. 属性がどんなものなのかを判定

と言った感じだろうか。

まずpタグの属性があるのかどうかを判定してみる。

preg_match_all("/<p([\s\w]+=\"(.*)\")?>(.*?)<\/p>/", $text, $matches)

正規表現はこうじゃないかな・・・。もっとスマートな表現があったら教えてほしい・・・。orz

この正規表現で上記の

<p style="text-align: center; margin-left: 40px;">...</p>

これをマッチさせると

//$matches
Array
(
    [0] => Array
        (
            [0] =><p style="text-align: center; margin-left: 40px;">...</p>
        )

    [1] => Array
        (
            [0] =>  style="text-align: center; margin-left: 40px;"
        )

    [2] => Array
        (
            [0] => text-align: center; margin-left: 40px;
        )

    [3] => Array
        (
            [0] => ...
        )

)

こんなものを吐き出してくれる。

$matches[2][0]にはプロパティと値のみが

$matches[3][0]にはpタグ内のノードが偶然にも上手い具合に格納されている。

念のため属性もプロパティと値に分けてみる。

preg_match_all("/([\w-]+)[:\s]+([\w\d]+)[\;\s]+/", $matches[2][0], $properties)

としてみた。

・・・。正規表現が合ってるのか分からんが、これで一応動いているようだ。

これで

//$properties
Array
(
    [0] => Array
        (
            [0] => text-align: center; 
            [1] => margin-left: 40px;
        )

    [1] => Array
        (
            [0] => text-align
            [1] => margin-left
        )

    [2] => Array
        (
            [0] => center
            [1] => 40px
        )

)

となってくれた。

これで後は置換でOKだった。

これだけで8hとか笑っちゃうわ。orz