TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Advanced PHP Programming (http://www.talkphp.com/advanced-php-programming/)
-   -   Variables in Regular Expession (http://www.talkphp.com/advanced-php-programming/1631-variables-regular-expession.html)

Wildhoney 12-05-2007 11:28 PM

Variables in Regular Expession
 
I have a question of my own! I found out yesterday that you can add so-called variables in your regular expressions, although technically they're more like naming schemes for your array indexes. They can be done like so:

php Code:
$szText = 123;
preg_match('/(?P<first>\d{1})(?P<second>\d{1})(?P<third>\d{1})/', $szText, $aMatches);
print_r($aMatches);

Which would output:


Code:

Array
(
    [0] => 123
    [first] => 1
    [1] => 1
    [second] => 2
    [2] => 2
    [third] => 3
    [3] => 3
)

My question is, aside from what the correct term for them are, is this: is there any way to prevent the function from also adding the numeric indexes to the array and leave you with a pure associative array?

Salathe 12-06-2007 02:13 AM

They're called named capturing groups (as opposed to just capturing groups or non-capturing groups). There are a few alternative syntaxes in RegEx-land for doing this, but (?P<name>...) is all that PHP can use (PCRE).

More information is available on the ever useful regular-expressions.info site or in the PHP Manual. As far as I'm aware, the numeric key cannot be omitted from the resulting array of matches. That said it's a trivial matter to parse that array to remove items with a numeric key if you really wanted to. :-)

Wildhoney 12-06-2007 02:57 PM

An interesting read, Salathe. Thanks for pointing me in the right direction! Before last night I've only managed to read the first few pages of any regular expression documentation. There is some excellent stuff in php.net's manual for regular expressions, such as all the \S, \n.

I know it's not really much of an issue with the numeric items, but I was merely wondering if there was a flag you could set which prevented it. I'm guessing there isn't, though.

Matt83 12-06-2007 03:27 PM

Quote:

Originally Posted by Salathe (Post 5525)
More information is available on the ever useful regular-expressions.info site or in the PHP Manual.

Thanks for the links ^^

Karl 12-06-2007 03:44 PM

I guess I should read up on some RegEx too. I started a book on it once, got about 2-3 chapters in and never went back. It's not a subject that particularly interests me, but the power of RegEx cannot be ignored, it is a must for any serious programmer.


All times are GMT. The time now is 11:20 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0