我试图创建一个函数,它接受一个字符串(包含简单的数学表达式),然后将每个部分拆分为一个数组。
例如,输入是2 + 3 * 7或2 – 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);
}当然,第一个例子使用的仅仅是爆炸,效果很好,但与另一个不一样。
发布于 2019-04-30 06:48:02
你可以试试这样- 基于堆栈中其他地方的答案。修改模式并添加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
)发布于 2019-04-30 06:47:36
您可以使用regex:
$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发布于 2019-04-30 06:41:39
您可以使用斯普利特(。就像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)用来从字符串中删除空白的地方。
https://stackoverflow.com/questions/55915081
复制相似问题