douyanguo7964 2017-11-17 01:04
浏览 26
已采纳

检测字符串中的括号中的价格(PHP)

I'm looking to analyse strings in PHP. They appear as such:

Premium Upgrade (€10.00)

I want to detect when a string contains '(€10.00)', however the price will change. Hence I'm guessing a RegEx for 'Bracket, Float, Bracket' The end result is I want to remove the price from the string, however, its possible something else may appear in the brackets e.g.

Premium Upgrade (Per Person)

And hence I can't just explode or substring on the first opening brackets. However, there could be two, or more, brackets e.g.

Premium Upgrade (Per Person) (€10.00)

Hence in this instance, I would need to output:

Premium Upgrade (Per Person)

Thus my high level flow would be:

  • Check string, does it contact brackets and float?
  • Yes, remove the brackets and float, leaving other brackets in place, proceed.
  • No brackets and float? Leave as is, proceed.

My pysedo code is:

//Get my string
$str = $meta->display_key;

//I need a RegEx here to detect my bracket and float e.g. (€X.YY)
if (strpos($str, '(') !== false) {
    //Need to remove brackets and float here, but leave all other brackets in place.
    $formatted_string  = substr($str, 0, strrpos($str, '('));
}

//Do nothing, the string doesn't match my criteria
else $display_key_formatted = $str; 
  • 写回答

2条回答 默认 最新

  • dongluedeng1524 2017-11-17 01:40
    关注

    To delete a price in brackets that is in the (+CURRENCY_SYMBOL+FLOAT_OR_INT_NUMBER+) you may use

    $res = preg_replace('~\s*\(\p{Sc}\d[.\d]*\)~u', '', $s);
    

    See the regex demo

    Details

    • \s* - 0+ whitespaces
    • \( - a (
    • \p{Sc} - any currency char
    • \d - a digit
    • [.\d]* - 0+ chars that are either . or a digit
    • \) - a )

    See the PHP demo:

    $re = '/\s*\(\p{Sc}\d[.\d]*\)/u';
    $str = ' TEXT (text) (€10.00)';
    $res = preg_replace($re, '', $str);
    echo $res; // =>  TEXT (text)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部