douyanguo7964 2017-11-17 09: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 09: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条)

报告相同问题?

悬赏问题

  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元