Help us understand the problem. What is going on with this article?

preg_replaceとmb_ereg_replace

More than 1 year has passed since last update.

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"
}
*/
horikeso
個人的な備忘録ばかりですが、よろしくお願いします。難しいことはよくわかりません!
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした