Strlen剥离每个[x]字符


Strlen to strip every [x] characters

我试着去掉下面每三个字符(在这个例子中是一个句号)是我最好的猜测,但我错过了一些东西,可能是次要的。也会这种方法(如果我能让它工作)比一个正则表达式匹配,删除?

$arr = 'Ha.pp.yB.ir.th.da.y';
$strip = '';
for ($i = 1; $i < strlen($arr); $i += 2) {
$arr[$i] = $strip; 
}

你可以这样做:

<?php
$oldString = 'Ha.pp.yB.ir.th.da.y';
$newString = "";
for ($i = 0; $i < strlen($oldString ); $i++) // loop the length of the string
{
  if (($i+1) % 3 != 0) // skip every third letter
  {
    $newString .= $oldString[$i];  // build up the new string
  }
}
// $newString is HappyBirthday
echo $newString;
?>

或者,如果您试图删除的字母总是相同的,则可以使用explosion()函数。

这可能行得通:

echo preg_replace('/(..)./', '$1', 'Ha.pp.yB.ir.th.da.y');

使其通用:

echo preg_replace('/(.{2})./', '$1', $str);

其中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})'./

我只使用array_map和一个回调函数。它看起来大概像这样:

function remove_third_char( $text ) {
    return substr( $text, 0, 2 );
}
$text = 'Ha.pp.yB.ir.th.da.y';
$new_text = str_split( $text, 3 );
$new_text = array_map( "remove_third_char", $new_text );
// do whatever you want with new array