douba2011 2013-06-08 20:21
浏览 63
已采纳

当正确/匹配时,正则表达式if-condition的套件不执行[关闭]

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>";
}
?>
  • 写回答

3条回答 默认 最新

  • dongmeng1868 2013-06-08 20:29
    关注

    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>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计