SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Zealot
    Join Date
    Nov 2005
    Posts
    181
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Named groups in regular expressions

    Hi all,

    I'm trying to match a string with a regular expression.
    Code:
    $regex = "^(<type>int|string|mixed)?(\(<length>([0-9]){1, }\)) (<name>(*)$";
    Here's what I need to do. I need to match a string for example "int(4) year" and be able to access it like:
    $match['type'] == "int",
    $match['length'] == "4",
    $match['name'] == "year"

    The string begins with "int", "string" or "mixed" and optionally can include a length "(any_number)" "whitespace" " name".

    I'm trying to preg_match() this but keep getting warnings. That may because my inability to do regexes.

    Can anyone lend me a hand?

    --- Edit:
    Code:
     ^(int|string|mixed)(\(([0-9])+\))? ([a-z])+
    This regular expression works in Regex Coach (this software is very helpful and is free) but not PHP... I get the warning "preg_match() [function.preg-match]: No ending delimiter '^' found in"
    Last edited by hannson; Oct 8, 2008 at 12:34. Reason: Added a regex.

  2. #2
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    This is how you do named groups in PHP: (?P<name_here>put_pattern_here)
    So maybe...
    ^(?P<type>int|string|mixed)(?:\((?P<length>\d+\))?(?P<name>.*)$
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  3. #3
    SitePoint Zealot
    Join Date
    Nov 2005
    Posts
    181
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    $regex '^(?P<type>int|string|mixed)(?:\((?P<length>\d+\))?(?P<name>.*)$';
    $matches = array();
    preg_match($regex$value$matches);
    var_dump($matches); 
    var_dump shows an empty array and I still get the error No ending delimiter '^' found in .

    That regex pretty much describes my needs but I'm doing something wrong here.

  4. #4
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    delimiters... prefix and sufix "/" to the regex
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  5. #5
    SitePoint Zealot
    Join Date
    Nov 2005
    Posts
    181
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks a lot!

    If anyone ends up here the working regex is:
    PHP Code:
    $regex '/^(?P<type>int|string|mixed)(?:\((?P<length>\d+\)))?(?P<name>.*)$/'


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •