PHP正则表达式匹配函数名称和参数与字符串像针(针|针)

时间:2014-04-16 14:38:55

标签: php regex

我使用如下所示的查询字符串过滤数据库结果:

attribute = operator(value | optional value)

我会用

$_GET['attribute'];

获得价值。

我认为正确的方法是使用正则表达式来获得其余的匹配。

首选输出为

print_r($matches);
array(
    1 => operator
    2 => value
    3 => optional value
)

操作符总是一个单词,由字母组成:like(),between(),in()。

值可以是许多不同的东西,包括字母,数字,空格逗号,引号等......

我被问到我的代码在哪里失败,并且因为它的工作效果不佳而没有包含太多代码。基于接受的答案,我能够制作一个几乎的正则表达式。

编辑1

$pattern = "^([^\|(]+)\(([^\|()]+)(\|*)([^\|()]*)";

编辑2

$pattern = "^([^\|(]+)\(([^\|()]+)(\|*)([^\|()]*)"; // I thought this would work.

编辑3

$pattern = "^([^\|(]+)\(([^\|()]+)(\|+)?([^\|()]+)?"; // this does work!

编辑4

$pattern = "^([^\|(]+)\(([^\|()]+)(?:\|)?([^\|()]+)?"; // this gets rid of the middle matching group.  

唯一剩下的问题是当第二个可选参数不存在时,仍然有一个空的$ matches数组。

1 个答案:

答案 0 :(得分:1)

此脚本带有输入"运算符(值|可选值)",返回您期望的数组:

<?php
    $attribute = $_GET['attribute'];
    $result = preg_match("/^([\w ]+)\(([\w ]+)\|([\w ]*)\)$/", $attribute, $matches);

    print($matches[1] . "\n");
    print($matches[2] . "\n");
    print($matches[3] . "\n");
?>

这假设你的价值观&#34;匹配[\w ]正则表达式(所有单词字符加空格),并且您指定的|是文字| ...