【问题标题】:How to split some numbers and math operator in PHP?如何在 PHP 中拆分一些数字和数学运算符?
【发布时间】:2019-04-30 06:28:03
【问题描述】:

我正在尝试创建一个函数,该函数接受一个字符串(包含简单的数学表达式),然后将每个部分拆分为一个数组。

例如输入是2 + 3 * 72 – 5 / 3.4,输出应该是["2", "+", "3", "*", "7"]["2", "-", "5", "/", "3.4"]

这是我的代码:

$input = "2 + 3 * 7";
$input = "2-5/3.4";

function splitExpression($string) {
    $result = explode (" ", $input);
    print_r ($result);
}

只使用爆炸,当然第一个例子效果很好,但与另一个不一样。

【问题讨论】:

标签: php string function


【解决方案1】:

您可以像这样尝试 - based upon answer elsewhere on stack。修改了模式,增加了preg_replace,使得结果不受输入字符串中空格的影响。

$input = '2 + 3 * 7';
$input = '2-5/3.4';


$pttn='@([-/+\*])@';
$out=preg_split( $pttn, preg_replace( '@\s@', '', $input ), -1, PREG_SPLIT_DELIM_CAPTURE );

printf('<pre>%s</pre>',print_r( $out, true ) );

将输出:

Array
(
    [0] => 2
    [1] => -
    [2] => 5
    [3] => /
    [4] => 3.4
)

更新:

$input = '2 + 5 - 4 / 2.6';


$pttn='+-/*';   # standard mathematical operators
$pttn=sprintf( '@([%s])@', preg_quote( $pttn ) ); # an escaped/quoted pattern

$out=preg_split( $pttn, preg_replace( '@\s@', '', $input ), -1, PREG_SPLIT_DELIM_CAPTURE );

printf('<pre>%s</pre>',print_r( $out, true ) );

输出:

Array
(
    [0] => 2
    [1] => +
    [2] => 5
    [3] => -
    [4] => 4
    [5] => /
    [6] => 2.6
)

【讨论】:

  • 你的意思是按照“BODMAS”规则吗?
  • 不,我不相信它会 - 但那不是问题的一部分,事实上,需要一个全新的问题
  • 您的回答无法解决上述问题,因为 - 首先计算 2-5,然后除...
  • 看看这个问题 - 特别是"The output should be like ....."
  • @RamRaider 你能向我解释更多关于$pttn='@([-/+\*])@'; 作为限制器的信息吗?因为当我更改/重新排序时,输出会发生变化。
【解决方案2】:

你可以使用正则表达式:

$matches = array();
$input="2 + 3 * 7 / 5 - 3";
preg_match_all("/\d+|[\\+\\-\\/\\*]/",$input,$matches);

此正则表达式搜索数字或运算符并将匹配项放入 $matches。 您可以通过标志编辑匹配数组的设计。

matches:
 + 0
     - 0 : 2
     - 1 : +
     - 2 : 3
     - 3 : *
     - 4 : 7
     - 5 : /
     - 6 : 5
     - 7 : -
     - 8 : 3

【讨论】:

  • 那个正则表达式无效。
【解决方案3】:

您可以使用str_split()。喜欢 str_split($str1);

$input = "2-5/3.4";
$input = "2 + 3 * 7";

function splitExpression($string) {
    //$result = str_split (string);
    $result = str_split (preg_replace('/\s+/', '', $string));
    return $result;
}
$arr1 = splitExpression($input);

preg_replace('/\s+/', '', $string) 用于从字符串中删除空格。

【讨论】:

  • 如果字符串是30 + 4 *2怎么办?还是40+3.4?还是$input 的第一个?这真的行不通。这只有在有整数、没有小数和没有大于 9 的数字时才有效。相当严格的限制。
猜你喜欢
  • 1970-01-01
  • 2013-08-30
  • 1970-01-01
  • 1970-01-01
  • 2015-09-30
  • 1970-01-01
  • 2017-03-18
  • 2013-07-12
  • 2014-01-15
相关资源
最近更新 更多