以下の 3 文字ごとに (例ではピリオド) を削除しようとしていますが、これは私の最善の推測であり、得たものに近いですが、おそらくマイナーな何かが欠けています。また、この方法は(私がそれを機能させることができれば)正規表現の一致よりも優れていますか?
$arr = 'Ha.pp.yB.ir.th.da.y';
$strip = '';
for ($i = 1; $i < strlen($arr); $i += 2) {
$arr[$i] = $strip;
}
これはうまくいくかもしれません:
echo preg_replace('/(..)./', '$1', 'Ha.pp.yB.ir.th.da.y');
汎用にするには:
echo preg_replace('/(.{2})./', '$1', $str);
このコンテキストでのwhere2
は、2 つの文字を保持し、次の文字を破棄することを意味します。
それを行う方法:
$old = 'Ha.pp.yB.ir.th.da.y';
$arr = str_split($old); #break string into an array
#iterate over the array, but only do it over the characters which are a
#multiple of three (remember that arrays start with 0)
for ($i = 2; $i < count($arr); $i+=2) {
#remove current array item
array_splice($arr, $i, 1);
}
$new = implode($arr); #join it back
または、正規表現を使用して:
$old = 'Ha.pp.yB.ir.th.da.y';
$new = preg_replace('/(..)\./', '$1', $old);
#selects any two characters followed by a dot character
#alternatively, if you know that the two characters are letters,
#change the regular expression to:
/(\w{2})\./