tags:

views:

35

answers:

1

I am trying to match a string like the following:

<input type="text" value="cbyEOS56RK3lOxtiCrhmWSkDuNWwrFN4" name="iden">

This is my code:

$pattern = '~value="(.+?)" name="iden"~';
preg_match($pattern, $page, $match);
print_r($match);

As you can probably see, I am trying to match the value in this HTML input. By what I know of regular expressions, .* will match as many characters as possible until it satisfies the next token (in this case ").

I have the name="iden" part in my regex because there are other HTML inputs on the page and I only want to match this one.

Problem is, I'm not getting any matches at all. $match is an empty array. And I know that $page has the right content because I can see it when I echo it.

Help fixing my regex is appreciated, thanks.

+1  A: 

Since you used the phrase "there are other inputs on the page", I assume you're trying to parse out this particular tag from a full HTML document. In that case, I recommend using a DOM parser rather than regular expressions (I'm not trying to be facetious with that link, there's just a lot of options so that seemed easiest). They are designed specifically for this purpose and will be a lot easier in the end.

If you want to try regex anyway, I would personally use ([^"]+) instead of (.+?):

$pattern = '~value="([^"]+)" name="iden"~';

Though this still doesn't address whatever is causing your problem, as your regex should match on that line.

eldarerathis
I don't fully agree with tihs. Depending on the task, a full-fledged DOM parser might well be overkill. A simple regex is often the best tool for a task like this.
Ben Lee
@Ben Lee: The DOM parser would more elegantly handle the arbitrary whitespace/newlines/etc that you refer to in your previous comment, though. If this was as simple as the question appears initially, then his regex ought to work, no?
eldarerathis
Good point. Agreed that a DOM parser is generally better if you're the whitespace is variable (a regex to account for optional whitespace everywhere can get really ugly).
Ben Lee
@Ben Lee: Yup, that's pretty much all I was getting at. If it really is "I need to match this line" then it should work, so I'm guessing it's something else...
eldarerathis