如何在php中分解字符串



我有一个这样的字符串-

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;
?>

当注释出现时,我正在编写regexp…

$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
$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

您可以访问字符串中的单个字符使用"方括号">

最新更新