dongpan1308 2018-02-04 22:13
浏览 6
已采纳

由操作员拆分数学公式但保留操作员

I'm looking to split the following strings based upon the operator between them. If there is parenthesis then we have to keep the entire parenthesis together.

Here's the types of strings I will have.

(1.25*1.5)-(10.5/2.15625)
(1.25*1.5)+10.75
1.25*(10.5/10.75)
1.25/10.5

The desired output I'm looking for is this

array(){
    [0]=>
    string = "(1.25*1.5)"
    [1]=>
    string = "-"
    [2]=>
    string = "(10.5/2.15625)"
}

array(){
    [0]=>
    string = "(1.25*1.5)"
    [1]=>
    string = "+"
    [2]=>
    string = "10.75"
}

array(){
    [0]=>
    string = "1.25"
    [1]=>
    string = "*"
    [2]=>
    string = "(10.5/10.75)"
}

array(){
    [0]=>
    string = "1.25"
    [1]=>
    string = "/"
    [2]=>
    string = "10.5"
}

this is what I have so far.

$expression_parts = preg_split('~([<>=]+)~', $expression, NULL, 
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY ) ;
  • 写回答

3条回答 默认 最新

  • dpwh11290 2018-02-04 22:51
    关注

    I'll show you a new trick (*SKIP)(*FAIL) this time. This technique is used to match and disqualify targeted substrings.

    Code: (Demo)

    $strings=[
        '(1.25*1.5)-(10.5/2.15625)',
        '(1.25*1.5)+10.75',
        '1.25*(10.5/10.75)',
        '1.25/10.5'
    ];
    foreach($strings as $string){
    //                                                  vvvvvvvv-capture and retain non-numeric characters (delimiters)
        var_export(preg_split('~\([^)]*\)(*SKIP)(*FAIL)|([^\d.])~',$string,NULL,PREG_SPLIT_DELIM_CAPTURE));
    //                          ^^^^^^^^^-match and disqualify parentheticals
        echo "
    ";
    }
    

    Output:

    array (
      0 => '(1.25*1.5)',
      1 => '-',
      2 => '(10.5/2.15625)',
    )
    array (
      0 => '(1.25*1.5)',
      1 => '+',
      2 => '10.75',
    )
    array (
      0 => '1.25',
      1 => '*',
      2 => '(10.5/10.75)',
    )
    array (
      0 => '1.25',
      1 => '/',
      2 => '10.5',
    )
    

    This will also perform very well on your input strings:

    preg_match_all('~\([^)]+\)|\d+(?:\.\d+)?|.~',$string,$out)?$out[0]:[]
    
    ~                #pattern delimiter
    \([^)]+\)        #match parenthetical expression (does not account for nested parentheticals)
    |                #or
    \d+(?:\.\d+)?    #match integers or floats (notice the ? makes the trailing portion optional
    |                #or
    .                #match one non-newline character that isn't caught by an earlier "alternative"
    ~                #pattern delimiter
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探