如果长度为奇数,如何在字符串数组元素的中间字符中打印*

时间:2017-08-25 15:54:39

标签: php arrays

我想在数组的奇数元素的中间元素中打印*。这是我的代码我没有得到我在内循环上写的条件是什么?如果字符长度是7那么我如何在4号码字符上打印*?

 $strings = array("abcdef","abcde","qwert","abcdef","bat");

 for ($i=0; $i <count($strings) ; $i++) { 

 $len = strlen($strings[$i]);

 if($len % 2 == 0)
  {
 echo "Chacater's are even<br>";
  }
else{

 $string = $strings[$i];

 for($j=0; $j<1; $j++)
 {
    $string[$j] = "*";
  }
echo $string."<br>";
  }

  }

2 个答案:

答案 0 :(得分:3)

根据我的理解,你需要用'*'替换数组中奇数长度元素的中间字符。此代码将为您提供所需的结果。

$strings = array("abcdef","abcde","qwert","abcdef");
    $count = count($strings);

    for ($i=0; $i<$count; $i++) { 
        $len = strlen($strings[$i]);
        if($len % 2 == 0){
            echo "Chacater's are even \n";
        }else{
            $string = $strings[$i];
            // find the center index
            $center = floor($len/2);
            // replace the center char with *
            $string = substr_replace($string, '*', $center,1);
            echo $string."\n";
        }
      }

Out put:

Chacater's are even 
ab*de
qw*rt
Chacater's are even 

答案 1 :(得分:0)

所以你想这样做

 <?php 
  $strings = array("abcdef","abcde","qwert","abcdef");
  foreach($strings as $key=> $value){
     $strlen = strlen($value);
     if($strlen%2 == 0){
       echo "\n".$value." :even length";
     }else {
       if($strlen > 1){
         $value[intVal($strlen/2)]="*";
       }
       echo "\n".$value." :odd length";
     }
  }
 ?>

演示:https://eval.in/850350

http://sandbox.onlinephpfunctions.com/code/1270a1e27b1148e4381ac7882a747ba592b328dc