Tbpgr Blog

Ruby プログラマ tbpgr(てぃーびー) のブログ

PHP | preg_replace

概要

preg_replace

詳細

正規表現を利用した文字列置換

サンプル

#!/usr/bin/env php
<?php
$target1 = <<< EOS
hoge
hige
hage
EOS;

$target2 = <<< EOS
hoge
huge
hage
EOS;
$pattern = '/(hoge)(.*)(hage)/s';
$replacement = '${1}髭ふげ${3}';
print(preg_replace($pattern, $replacement, $target1));
print("\n");
print(preg_replace($pattern, $replacement, $target2));

出力

hoge髭ふげhage
hoge髭ふげhage

Rubyと比較

# encoding: utf-8
target1 = <<EOS
hoge
hige
hage
EOS

target2 = <<EOS
hoge
huge
hage
EOS
$pattern = /(hoge)(.*)(hage)/m;
$replacement = '$1髭ふげ$3';
puts target1.gsub($pattern, $replacement);
puts target2.gsub($pattern, $replacement);