2

I'm having a tough time sorthing this out. I'm working with a custom plugin system that presents things like this:

<plugin:class:method var1='hello', var2='yes' />

But, ':method' and the variables do not have to exist - only the 'class' is required. For instace, this should still be ok:

<plugin:class />

The problem I'm having is how to I get the regex to conditionally return things when the method and/or variables do not exist. So far, I can get results when all the pieces exist, but not otherwise - this is where I'm at (struggling on the first conditional):

$f = "/<plugin:(?P<class>\w+)(?(?=^:)?P<method>\w+)\s+(.*)\/>/sUi";

Things are working very well with the following code, it's simply a matter of being able to return all the pieces with the conditionals:

preg_replace_callback($f, array($this, 'processing'), $text);

Hope this makes some sense - and is even possible. Thanks.

1
  • You are not designing a regular language. use a parser for context-free grammar (yes, I know some regex parsers support recursion … – but it's not the right tool™ for the job) Commented Sep 25, 2011 at 19:42

2 Answers 2

1

The easiest and most maintainable way to do this would be to just get the whole plugin:class:method string with a simple /plugin:\S+/ expression, then explode(':', $string).

So, instead of the code above, you'd have something like:

$f = "/<plugin:(\S+)\s+(.*?)\/>/sUi";
if (preg_match($f, $string, $matches)) {
    $parts = explode($matches[1]);
    if (!in_array('method', $parts))
    {
        // do whatever needs done if "method" is not present
    }
    // ...
}
Sign up to request clarification or add additional context in comments.

4 Comments

"most maintable" - I'd like to know more about this. Is it because I'm using PCRE extended thing that's not available in all situations?
@telefiend, I'm saying that this would be maintainable because the code will be very easy to read, understand and extend, than a complicated regular expression that would do the same thing. Added example.
I understand that. I have actually done it your way in the past but thought it might be more easy if the regex was more precise in it's output. A problem of style I suppose - good thing to think about.
$f = "/<plugin:(\S+)\s+(.*)\/>/sUi"; Final solution, as suggested. Keep it simple. Thanks.
0

Shouldn't (?=^:) be (?!:) ?

1 Comment

code"/<plugin:(?P<class>\w+)(?(?!:)?P<method>\w+)\s+(.*)\/>/sUi"code - doesn't do the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.