LoginSignup
2
3

More than 5 years have passed since last update.

Perl正規表現にある$`$'をPHPでするには PREG_OFFSET_CAPTURE

Last updated at Posted at 2016-01-27

HTML::Template風なのを作りたくてはまったこと。
HTMLを<TMPL_HOGE keyname>タグでちょん切りたいのにPerlの\$`\$'みたいな特殊変数がPHPにはない!?

PHP
preg_match('/<(\/?TMPL_\w+)\s*(\w*)\s*>/s', $html, $m, PREG_OFFSET_CAPTURE);
list($all, $tagname, $key) = $m;
$text   = substr($html, 0, $all[1]);                # 一致より前 $`
$html   = substr($html, $all[1] + strlen($all[0])); # 一致より後 $'

PREG_OFFSET_CAPTUREを付けると$mが2次元配列になってこんな構造で来るので
substrで元の\$htmlを切り取って\$``\$'のかわりにした。

PHP
$m = array(
    array(allval, allpos),
    array(tagval, tagpos),
    array(keyval, keypos)
);

$_tag  = substr($html, 0, allpos);               # TMPLタグより前 $`
$tag_  = substr($html, allpos + strlen(allval)); # TMPLタグより後 $'

perlだとこう。やっぱPerlて暗号みたい

Perl
$html =~ m|<(/?TMPL_\w+)\s*(\w*)\s*>|s;
$_tag = $`; # TMPLタグより前 $`
$tag_ = $'; # TMPLタグより後 $'
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3