douhuang9886 2016-11-19 02:23
浏览 103

在字符串中添加带下划线的大写字符

I am trying to convert a string e.g. WhatAWonderfulDay into a lowercase string where all uppercase characters are preceded with underscores e.g. what_a_wonderful_day. Also, I am trying to make a reverse algorithm that translates let's say a_quick_fox into AQuickFox.

I am providing my implementation, though I know it's inefficient. Any ways to simplify these two operations?

// 1. WhatAWonderfulDay -> what_a_wonderful_day

$chars = str_split('WhatAWonderfulDay');
$result = "";
foreach($chars as $char) {
    if (ctype_upper($char) && !empty($result))
        $result .= "_"
    $result .= $char;
}
echo $result;

// 2. a_quick_fox => AQuickFox

$chars = str_split('a_quick_fox');

$result = "";
$should_make_upper = true;
foreach($chars as $char) {
    $result .= (should_make_upper) ? strtoupper($char) : $char;
    $should_make_upper = false;
    if ($char == "_")
        $should_make_upper = true;
}
echo $result;
  • 写回答

2条回答 默认 最新

  • duai1683 2016-11-19 02:44
    关注

    Here is some simpel code that will get you started:

    $string = "AQuickTest";
    
    preg_match_all("/[A-Z]/",$string,$matches);
    
    foreach($matches[0] as $match){
        $string = str_replace($match,"_".strtolower($match),$string);
    }
    
    echo $string;
    

    The result is: _a_quick_test

    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示