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条)

报告相同问题?

悬赏问题

  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow