views:

48

answers:

3

I have a text:

$test = <<<START
 DOTHIS themsp1
  @theint =    431,
  @theText = "%dumdum%",
  @operator = 'ANY',
  @crossCheck = 'PLUS'


START;

The filter:

$regEx = '/@(.*)=(.*)[,]*?/';
preg_match_all($regEx,$test,$vars,PREG_SET_ORDER);
print_r($vars);

The Output:

Array
(
    [0] => Array
        (
            [0] => @theint =  431,
            [1] => theint 
            [2] =>   431,
        )

    [1] => Array
        (
            [0] => @theText = "%dumdum%",
            [1] => theText 
            [2] =>  "%dumdum%",
        )

    [2] => Array
        (
            [0] => @operator = 'ANY',
            [1] => operator 
            [2] =>  'ANY',
        )

    [3] => Array
        (
            [0] => @crossCheck = 'PLUS'
            [1] => crossCheck 
            [2] =>  'PLUS'
        )

)

I don't want commas OR the whitespace in the output :( .. The problem is that the commas are optional;

+2  A: 
/@(.*?)\s*=\s*(.*?),?/

Add \s* in the appropriate places to match whitespace. Use a question mark for .*? to match non-greedily. A non-greedy match matches as short a match as possible, so (.*?),? will let the comma on the right match a comma rather than the .* capturing the comma.

John Kugelman
A: 

You should be more specific than just using ., for example:

/@([a-zA-Z]+)[ \t]*=[ \t]*([0-9]+|"(?:[^\\"]|\\.)*"|'(?:[^\\']|\\.)*')[ \t]*,?/

Here [a-zA-Z]+ specified the name as a sequence of alphabetic characters. That is then followed by the = that may be surrounded by spaces or tabs. And then the value is either a number ([0-9]+, sequence of one or more digits) or a quoted string that may contain escape sequences ("(?:[^\\"]|\\.)*"|'(?:[^\\']|\\.)*'), followed by optional spaces or tabs.

Gumbo
+1  A: 

In your regex $regEx = '/@(.*)=(.*)[,]*?/'; the 2nd (.*) is greedy and will match the comma, since the comma as you wrote it is optional.

Untested, this regex will allow optional spaces around the equal sign but not include them in the capture '/@([^\s=]+)\s*=\s*([^\s,]+)\s*,?/' It also allows space between the value and the comma.

Stephen P
Thank you.. It works :)
Stewie