Regex Match


I am very new to PHP (started this week) and I have a problem (I’m coming from C/C++/C# so PHP is a bit strange for me).

What I want to do is Regex.Match thingy, and on I found proper function (preg_match())

So what I want to do is from variable $response which contains something like: GALX=CVfeZW_855M; extract the GALX value from = to ;

So what I tried is:
preg_match(‘GALX=([^;])’, $response, $matches, “”, 0);

But I get null match, so I’m wondering what I am doing wrong.


if(1 === preg_match('~(?<=GALX=)([^;]+)~', 'GALX=CVfeZW_855M;', $matches)){
    echo $matches[1]; #CVfeZW_855M

Aha, so if preg_match returns int 1 and 1 only… can I do if(preg_match() > 0) as well? Although I totally forgot about $matches beeing an array.

But I don’t understand this pattern expression (~(?<=GALX=).+~)…

Ok, it worked, but I get too much of an output.

I get resSroX68nKMvQ;Path=/accounts;Secure when I should only get till “;” so resSroX68nKMvQ

[fphp]preg_match[/fphp] can return 1 (match), 0 (no match) or false (error).

It’s a Positive lookbehind. It matches a group before your main expression without including it in the result. :wink:

Does my amended pattern work? :shifty:

Partially it works. It outputs too much content. I just need GALX value till semicolon “;”

Do you have a sample string?

Can you confirm you’re using…

if(1 === preg_match('~(?<=GALX=)([^;]+)~', 'GALX=CVfeZW_855M;', $matches)){
    echo $matches[1]; #CVfeZW_855M

You removed part of the regex Anthony posted, or he edited the post. The [^;] part.

This is part of variable:

charset=UTF-8 Set-Cookie: GALX=fc9nuw1krZY;Path=/accounts;Secure Cache-control:

With ‘~(?<=GALX=).+~’ as pattern I get:

While ‘~(?<=GALX=)([^;]+)~’ WORKS.

Thanks a TON :slight_smile:

I don’t quite understand the pattern, its very different from patterns I used in C#. Is there any good resource you suggest where I could learn patterns?

I’m asking, as I need to make another match:
<input type=“hidden” name=“dsh” id=“dsh” value=“5651071537274271064” />

This time I need value of element with id=“dsh”. How would the pattern go so I get output of 5651071537274271064 is a good source.