我有一个像这样的字符串-
Course_13_Laravel_Batch_15_Day_22
我想获得此输出
C-13-L-B-15-D-22
我该怎么做? 这是我的代码-
<?php
$string = "Course_13_Laravel_Batch_15_Day_22";
$dim = explode(" ", $string);
$str = "";
foreach($dim as $item){
if(is_numeric( $item)){
$str = $str."-".substr($item, 0, 2);
}else{
$str = $str."-".substr($item, 0, 1);
}
}
$str = substr($str,1);
echo $str;
?>
答案 0 :(得分:3)
当评论进入时,我只是在做正则表达式...
$string = "Course_13_Laravel_Batch_15_Day_22";
echo preg_replace(array('/([a-zA-Z]).*?_/', '/([0-9]+)_/'), '$1-', $string);
输出:
C-13-L-B-15-D-22
答案 1 :(得分:0)
$string='Course_13_Laravel_Batch_15_Day_22';
$data=explode('_',$string); // since there is underscore to differ every work/number i use it as my delimiter
foreach($data as $row){
if(is_numeric($row)){ //check if my array field value is a number
$newArray[] = $row;
}
else{
$newArray[]= $row[0]; //You can access single characters in a string by using "square brackets"
}
}
$data=implode('-',$newArray); // merge array fields to a string using implode function and dash delimiter
echo $data;
输出为:
C-13-L-B-15-D-22
您可以访问字符串中的单个字符 通过使用“方括号”