0

I have this segment of xml.

<condition name="gender" value="male">
    <condition name="somethingelse" value="somevalue">Target string</condition>
</condition>

You can see that these are nested.

What I need to do is get the middle condition containing the 'target string'.

People will probably suggest to use an xml parser or something, but I want to do it with regex.

I messed around with a regex but I just do not know them well enough yet.

Take this for example.

$regex = '<condition name="[a-z0-9]+" value="[a-z0-9]+">([^<>].*?)<\/condition>';
preg_match_all ( '/' . $regex . '/i', $haystack, $stuff );

What I was trying to do there was match the tags but ignore anything that contains < or > thus avoiding anything that does not contain text.

My example does not work, it's just to show where I got to and now I am stuck.

All it does is give this match, so I am part way there :

<condition name="gender" value="male"> <condition name="somethingelse" value="somevalue">Target string</condition>

Could anyone help please ?

3
  • 1
    If you know that you actually have XML, how did you come to the conclusion to use a regex for it? Commented Nov 9, 2014 at 20:39
  • 1
    "People will probably suggest to use an xml parser or something, but I want to do it with regex." Why? Is this a learning exercise? Commented Nov 9, 2014 at 20:42
  • It's XML yes, it describes an algorithm - if I use the xml parser I lose parts of the data that I need. Commented Nov 9, 2014 at 20:47

1 Answer 1

1

Here is a regex that will work (at least in the simple use case you've outlined above):

$regex = '/<condition name="[a-z0-9]+" value="[a-z0-9]+">([^<>]*)<\/condition>/';

Note that I removed the question mark (not sure what it was intended for) and put the asterisk after the [^<>] rather than having a period after. The string [^<>]* says to match zero or more characters not in the set {<, >}.

Sign up to request clarification or add additional context in comments.

Comments

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.