【问题标题】:Weird Regex issue - Proper Debugging Methods for PHP [closed]奇怪的正则表达式问题 - PHP 的正确调试方法 [关闭]
【发布时间】:2012-11-05 14:25:04
【问题描述】:

谁能解释为什么这个正则表达式会失败?它适用于在线 RegEx 测试器

http://www.spaweditor.com/scripts/regex/index.php 和我一样使用 PHP preg_match

这里几乎是所有相关代码。

是的,正则表达式可以正常工作,但 php 代码不能。我需要记住什么时候应该工作,而不是通常是一个错字。在这种情况下,我通过输入. 而不是, 将我的模式连接到我的字符串,我发现这很难注意到错字。因此,我似乎无法找到语法错​​误的一个技巧是重新输入有问题的代码。当然,在这种情况下,我的拼写错误并没有导致语法无效。

我可能应该做的另一件事是检查 apache 错误日志,因为 preg_match 接收到的参数数量不正确应该会导致错误。

我不习惯使用 ajax 调用返回 json 的 php 脚本,而且我不习惯看不到生成的 php 错误。过去在使用 java 客户端时,我一直使用 php curl 客户端来测试 web 服务的响应。我很着急,跳过了这个项目的那一步。

您使用什么方法来正确调试您的 php?

//$colors  = mysql_real_escape_string($_POST['color']);
$colors='333333,cbafff';

 function addcolor($colors,$cart_id, $dbh) {
    //insert color or scheme into cart
    //If succeeds return success, if fail return failure
    $stmt2=$dbh->prepare("INSERT IGNORE INTO cart (cart_id,item_id) values (:cart_id,:item_id)");
    $stmt2->bindValue(':cart_id',$cart_id,PDO::PARAM_INT);
    $color_array=split(",",$colors);
    foreach ($color_array as $color) {
        $color=trim($color);

        if (!preg_match("/^[A-Fa-f0-9]{6}$/".$color)) {
            return array("result"=>"error: Invalid Color $color");
            break;
        }
        $stmt2->bindValue(':item_id',$color,PDO::PARAM_STR);
        if (!($stmt2->execute())) {
            return array("result"=>"failure ". $stmt2->getCode());
            break;
        }
    }
    return array("result"=>"success");
}

jQuery 脚本

// to use surround anchor tags with div (id=colors). Set color or scheme id as href value. On click the item is posted to the web service.
// To do improve response handling from webservice.

$(document).ready(function(){
    $("#img a").live("click", function(event) {
        event.preventDefault();
        var item = $(this).attr( 'href' );
        var rev = $(this).attr('rev');
        var action ="add";
        if (rev == "1") {
            action = "add";
            $(this).attr('rev',"2");
        }
        else {          
            action = "remove";
            $(this).attr('rev',"1");
        }
        var jqxhr = $.post("webservice.php", { action: action, color: item }, function(data) {
            var result=data.result;
            if (result!="success") {
                alert(result);
            }
        }, "json")
        .error(function() {         
            alert("error: unable to contact web service"); 
        });
    });
});

【问题讨论】:

  • 它工作正常:3v4l.org/prSLa
  • 对我来说也很好用——你很可能在$color 有一些你不期望的东西。尝试var_dump 并检查。
  • return smth; break; - 什么?
  • 为什么我的问题被否决了?
  • @Codeguy007 人们正在投票否决您的问题,因为您的示例运行良好。你的问题在别处。

标签: php jquery regex


【解决方案1】:

这一行是错误的,你是在连接而不是给 preg_match 提供第二个参数:

preg_match("/^[A-Fa-f0-9]{6}$/".$color)

preg_match("/^[A-Fa-f0-9]{6}$/", $color)

【讨论】:

  • 嘿,你为什么不接受我的回答?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-14
  • 2013-07-13
  • 1970-01-01
相关资源
最近更新 更多