doq70020 2014-05-20 10:17
浏览 87
已采纳

PHP:获取字符串的子字符串从'%'开始到第3次出现

I got a different strings with lists of percentages:

'51% 20% 19% 6% 3% 2% 2% ...'

How can I cut the string to:

'51% 20% 19%'

Maybe some regex?

  • 写回答

1条回答 默认 最新

  • douwei1174 2014-05-20 10:27
    关注

    You could match up until the 3rd occurrence of the percent sign.

    $str = '51% 20% 19% 6% 3% 2% 2%';
    preg_match('/^(?:[^%]*%){3}/', $str, $match);
    echo $match[0];                 //=> "51% 20% 19%"
    

    A verbose way would be..

    $str = '51% 20% 19% 6% 3% 2% 2%';
    $val = explode(' ', $str);
    echo "$val[0] $val[1] $val[2]"; //=> "51% 20% 19%"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部