I'm trying to echo something if a regex is matched in a string in PHP.
When I do if(true){//...}
the suite executes, but when I do if(regex){//..}
it is not working. By which I mean, the echo that is inside the suite is not executing.
What am I doing wrong?
Basically what I trying to do is echo something if $query looks like 2+2, 3* 5, or 4.0 / 1.2
Here is what is working:
<?php
if(true){
echo "<div class=\"calc\">Mathematical Operation</div>";
}
?>
And here is what is not working even though it should match $query, which is 2+ 2:
<?php
if(preg_match('/(\d+)(\s)*([+/*-])(\s)*(\d+)/', $query)){
echo "<div class=\"calc\">Mathematical Operation</div>";
}
?>
To match all of your example strings, like this one 4.0 / 1.2
, you will also need to change up how you match your digits to allow for floating point. The following regex will match "343.4" etc, which your current regular expression won't.
if (preg_match('/(\d+(\.\d+)?)\s*([*+\/-])\s*(\d+(\.\d+)?)/',$query)){
echo "<div class=\"calc\">Mathematical Operation</div>";
}
Read what the warning tells you:
PHP Warning: preg_match(): Unknown modifier '*' in php shell code on line 1
It means that there's going something wrong before an *
.
In this case it's the unescaped delimiter /
(as you can guess from the unknown modifier
).
Use:
// ---------------------------v (note the backslash here to escape the delimiter)
if (preg_match('/(\d+)(\s)*([+\/*-])(\s)*(\d+)/', $query)){
echo "<div class=\"calc\">Mathematical Operation</div>";
}
try this regex pattern:
/^\s*[0-9\.]+\s*[\+\-\*\/]\s*[0-9\.]+\s*$/
it should match the operations separately, i.e:
2+2
3* 5
4.0 / 1.2
the input should be like:
$query = "2+2"; //or 3* 5 etc
if(preg_match('/^\s*[0-9\.]+\s*[\+\-\*\/]\s*[0-9\.]+\s*$/', $query)){
echo "<div class=\"calc\">Mathematical Operation</div>";
}