doudengshen5591 2014-07-09 21:52
浏览 28
已采纳

修改字符串的长度,使其中的某些字符串计为1

Can't seem to figure out how to do this one. Given a string I want to return the length of that string... simple enough, but I also want an array of 'search' strings within it to only count as one.

$string = 'this is [Enter]a test example of [Enter]something.';

//this can contain any number of different strings
$replace = array(
    '[Alt]',
    '[Backspace]',
    '[Ctrl]',
    '[Del]',
    '[Down]',
    '[End]',
    '[Enter]'
);

expected output for the above would be :

$string = 'this is [Enter]a test example of [Enter]something.';

// would be 50
$norm_length = strlen($string);

//where all [x]'s in above array count as 1
$length = 38;
  • 写回答

3条回答 默认 最新

  • douan2478 2014-07-09 22:03
    关注

    Simple replace every of your keywords with a character of length one:

    $string = 'this is [Enter]a test example of [Enter]something.';
    
    //this can contain any number of different strings
    $replace = array(
        '[Alt]',
        '[Backspace]',
        '[Ctrl]',
        '[Del]',
        '[Down]',
        '[End]',
        '[Enter]'
    );
    
    echo strlen(str_replace($replace, "_", $string));
    

    (str_replace takes an array as search - no need for regex)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!