2012-06-22 35 views
0

我有一個與php相關的問題。如何編寫pcre模式以匹配特定標記

我必須爲特定文件編寫一個小解析器,我不知道正則表達式,所以我需要一些幫助。

這是輸入...

blah blah [{img:xyzname}] one more blah blah[{root}] 
and [{php:<?php ...echo 'phpcode';......?>}] 

...所以我有我的替換這些值,所以這裏是我做過什麼......

$alt=preg_replace_callback('|\[{(.*[^}\]])}\]|iU', 
             function ($match){ 
              $m=explode(':',$match[1]); 


               switch($m[0]){ 

                case 'img': 
                  return $m[1] 
                break; 
                case 'php': 
                  // i want that php code here in $m[1] but i am getting nothing 
                break; 
                default: 
                  return 'UNDEFINED'; 
                break; 
               } 
              } 
             },$this->content); 
      $this->content=$alt; 

我試過很多時間與許多patter和許多測試,但我注意到,我變得空或沒有,只有當我的[{php:<?php .....?>}] contains <? and only when I put < ?

+0

我也發現這個模式,但<?仍然是問題 | \ [{[^} \]] +} \] | iU –

+0

但它在regexbuddy中運行良好 是誰在這種情況下滑動php標籤 –

回答

1
preg_match_all('/\[{(\w+):((?:(?!}]).)*)}]/', $this->content, $matches); 
print(htmlspecialchars(var_export($matches, true))); 

如果你想在這個瀏覽器記住<和>獲取視爲標籤,除非你有& LT代替它們;和& gt ;.這就是我使用htmlspecialchars()的原因。使用你的輸入我得到這個:

array (
    0 => 
    array (
    0 => '[{img:xyzname}]', 
    1 => '[{php:<?php ...echo \'phpcode\';......?>}]', 
), 
    1 => 
    array (
    0 => 'img', 
    1 => 'php', 
), 
    2 => 
    array (
    0 => 'xyzname', 
    1 => '<?php ...echo \'phpcode\';......?>', 
), 
)