LoginSignup
25
26

More than 5 years have passed since last update.

preg_replace/preg_filterでループ処理を省略する

Posted at

プレフィックスを付加

$before = ['a', 'b', 'c'];
$after = preg_replace('/^/', 'Prefix:', $before);
var_dump($after);
/*
array(3) {
  [0]=>
  string(8) "Prefix:a"
  [1]=>
  string(8) "Prefix:b"
  [2]=>
  string(8) "Prefix:c"
}
*/

サフィックスを付加

$before = ['a', 'b', 'c'];
$after = preg_replace('/$/', ':Suffix', $before);
var_dump($after);
/*
array(3) {
  [0]=>
  string(8) "a:Suffix"
  [1]=>
  string(8) "b:Suffix"
  [2]=>
  string(8) "c:Suffix"
}
*/

プレフィックスとサフィックスを付加

$before = ['a', 'b', 'c'];
$after = preg_replace('/^.*$/s', 'Prefix:$0:Suffix', $before);
var_dump($after);
/*
array(3) {
  [0]=>
  string(15) "Prefix:a:Suffix"
  [1]=>
  string(15) "Prefix:b:Suffix"
  [2]=>
  string(15) "Prefix:c:Suffix"
}
*/

条件を満たすものだけを加工しながら抽出

大文字だけを対象にする
$before = ['a', 'A', 'b', 'B', 'c', 'C'];
$after = preg_filter('/\A[A-Z]++\z/', 'Prefix:$0:Suffix', $before);
var_dump($after);
/*
array(3) {
  [1]=>
  string(15) "Prefix:A:Suffix"
  [3]=>
  string(15) "Prefix:B:Suffix"
  [5]=>
  string(15) "Prefix:C:Suffix"
}
*/
25
26
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
25
26