7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

preg_replaceとmb_ereg_replace

Last updated at Posted at 2018-04-16

preg_replacemb_ereg_replaceどっちを使うか。

後方参照を使いたいならpreg_replace
使う必要がないなら好きな方で。

preg_replace

  • 置換パターンは文字列もしくは配列
  • 置換対象は文字列もしくは文字列の配列
  • 返り値
  • 結果の文字列(マッチするものがなければそのまま)
  • エラー時にNULLを返す
  • 引数が配列の場合は配列
  • 後方参照が使える ${0}${1}

${99}までは存在しない場合は空文字として認識される(エラーは出ない)
${99} → ''
${100} → '${100}'
$100 → '0' ${10}'0'に認識される ${10}が存在しなければ'0'に認識される

mb_ereg_replace

  • 置換パターンは文字列
  • 置換対象は文字列
  • 返り値
  • 結果の文字列(マッチするものがなければそのまま)
  • エラー時にFALSEを返す
  • パターン修飾子を設定する部分(//u)が不要
  • 後方参照が出来なかった

preg_replaceの動作例

preg_replace('/b(c)/u', '${0}${1}', 'abcdef1');

// string(8) "abccdef1"
preg_replace('/b/u', '', 'abcdef1');

// string(6) "acdef1"
preg_replace('/b/u', '', ['abcdef1', 'abcdef2']);

/*
array(2) {
  [0]=>
  string(6) "acdef1"
  [1]=>
  string(6) "acdef2"
}
*/
preg_replace(['/b/u', '/d/u'], ['B', 'D'], ['abcdef1', 'abcdef2']);

/*
array(2) {
  [0]=>
  string(7) "aBcDef1"
  [1]=>
  string(7) "aBcDef2"
}
*/
preg_replace(['/b/u', '/d/u'], ['B'], ['abcdef1', 'abcdef2']);

/*
array(2) {
  [0]=>
  string(6) "aBcef1"
  [1]=>
  string(6) "aBcef2"
}
*/
preg_replace(['/b/u'], ['B', 'D'], ['abcdef1', 'abcdef2']);

/*
array(2) {
  [0]=>
  string(7) "aBcdef1"
  [1]=>
  string(7) "aBcdef2"
}
*/
preg_replace(['/b/u', '/d/u'], '', ['abcdef1', 'abcdef2']);

/*
array(2) {
  [0]=>
  string(5) "acef1"
  [1]=>
  string(5) "acef2"
}
*/
7
2
1

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
7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?