簡體   English   中英

任何PHP字符串函數做這樣的事情?

[英]Any php string function to do something like this?

$length = strlen($s);

if($length == 10)
{

  $newval = '';
  for($i = 0; $i < 10; $i++)
  {

    $newval .= $s[$i];

    if($i == 2 || $i == 5)  
    {
       $newval .= '-';
    }

  }

}

如果有人知道我將使用哪種字符串函數,請告訴我。

當然,您可以使用substr完成此操作:

if(strlen($s) == 10) {
   $s = substr($s, 0, 3) . '-' . substr($s, 3, 3) . '-' . substr($s, 6);
}

鍵盤示例

簡單的字符串操作應保持簡單,因此請使用最簡單的解決方案:

$str = substr($input, 0, 3).'-'.substr($input, 3, 3).'-'.substr($input, 6);

但是像往常一樣,有幾種方法可以給貓蒙皮,因此您可以選擇。 喜歡:

$str = sprintf('%s-%s-%s', substr($input, 0, 3), substr($input, 3, 3), substr($input, 6));

或者

$str = preg_replace('/^(.{3})(.{3})(.*)$/', '\1-\2-\3', $input);

或者

$str = preg_split('//', $input);

if (5 > count($chrs)) {
   array_splice($chrs, 4, 0, '-');
}

if (3 > count($chrs)) {
   array_splice($chrs, 2, 0, '-');
}

$str = implode('', $chrs);

substr?

if(strlen($s) == 10)
{
   $newval.=substr($s,0,3)."-".substr($s,3,3)."-".substr($s,6,4);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM