开发者

Trying to split a string in 3 variables, but a little more tricky - PHP

开发者 https://www.devze.com 2023-01-29 03:31 出处:网络
Having pretty much covered the basics in PHP, I decided to challenge myself and make a simple calculator. After some attempts I figured it out, but I\'m not entirely content with it. I want to make开发

Having pretty much covered the basics in PHP, I decided to challenge myself and make a simple calculator. After some attempts I figured it out, but I'm not entirely content with it. I want to make开发者_StackOverflow it more user friendly and have the calculator input in just one box, very much like google search.

So one would simply type: 5+2 and recieve 7.

How would I split the string "5+2" into three variables so that the math functions can convert the numbers into integers and recognize the operator, as well as accounting for the possibility of someone using spaces between the values as well?

Would you explode the string? But what would you explode it with if there are no spaces? I've also stumbled upon the preg_split function, but I can't seem to wrap my head around or know if it's suitable to solve this problemt. What method would be the best option for this?


$calc = "5* 2+ 53";
$calc = preg_replace('/(\s*)/','',$calc);
print_r(preg_split('/([\x28-\x2B\x2D\x2F])/',$calc,-1,PREG_SPLIT_DELIM_CAPTURE));

That's my bid, resulting in

Array
(
    [0] => 5
    [1] => *
    [2] => 2
    [3] => +
    [4] => 53
)


You may need to use some clever regex to split it something like:

$myOutput = split("(-?[0-9]+)|([+-*/]{1})|(-?[0-9]+)");

I haven't tested that - just an semi-psuedo-ish example sorry :-> just trying to highlight that you will need to remember that your - (minus) operator can appear at the start of an integer to make it a negative number so you could end up with problems with things like -1--21 which is valid but makes your regex rules more complicated.


You will have to split the string using regular expressions. For example a simple regex for 5+2 would be:

\d\+\d

Check out this link. You can create and validate your regular expressions there. For a calculator it will not be that difficult.


You've got the right idea with preg_split. It would work something like this:

$values = preg_split("/[\s]+/", "76  +    23");

The resulting array will contain values that are NOT whitespace:

Values should look like this: $values[0]: "76" $values[1]: "+" $values[2]: "23"

the "/[\s]+/" is a regular expression pattern that matches any whitespace characters one or more times. Howver, if there are no whitespaces at all, preg_split will just return the original "5+2" as a single string in the first element of the array. i.e.:

$values[0] = "5+2"
0

精彩评论

暂无评论...
验证码 换一张
取 消