Reputation: 1237
I have a $html
variable containing a lot of html code and I'm trying to extract the value from a certain parameter (this can be the value, or the class, etc.) out of an input field based on its id.
An example of the code I'm trying to find:
<input type="text" autocomplete="" name="confirmedEmailAddress" id="emailaddress" maxlength="60" value="[email protected]" class="txt-box txtbox-m " aria-describedby="" aria-required="true" disabled="disabled" />
I'm trying to build a regex that extracts the value ([email protected]
) out of it, by telling it to find the value out of all <input>
where id="emailaddress"
- with wildcards between input and id, and between id and value (the only thing for sure is that input is before id which is before value).
Here is my current PHP code (using preg_match_all because it's supposed to become a function I can reuse in cases where there are several fields):
$pattern = '<input(.*)id="emailaddress"(.*)value="(.*?)"';
preg_match_all('/'.$pattern.'/si',$html,$matches);
I've been trying variations but I either get the first input field or no match. Any help welcome! Thanks in advance.
Upvotes: 1
Views: 14454
Reputation: 51
If you want to get only the value try this:
$string = '<input type="text" autocomplete="" name="confirmedEmailAddress" id="emailaddress" maxlength="60" value="[email protected]" class="txt-box txtbox-m " aria-describedby="" aria-required="true" disabled="disabled" />';
$pattern = '/<input(?:.*?)id=\"emailaddress\"(?:.*)value=\"([^"]+).*>/i';
preg_match($pattern, $string, $matches);
var_dump( $matches[1] );
Upvotes: 3
Reputation: 2604
Should be a rather simple one
$string = '<input type="text" autocomplete="" name="confirmedEmailAddress" id="emailaddress" maxlength="60" value="[email protected]" class="txt-box txtbox-m " aria-describedby="" aria-required="true" disabled="disabled" />';
$pattern = '/<input(.*?)id=\"emailaddress\"(.*)value=\"(.*?)\"/i';
preg_match_all($pattern, $string, $matches);
var_dump($matches);
That gives me:
array (size=4)
0 =>
array (size=1)
0 => string '<input type="text" autocomplete="" name="confirmedEmailAddress" id="emailaddress" maxlength="60" value="[email protected]"' (length=126)
1 =>
array (size=1)
0 => string ' type="text" autocomplete="" name="confirmedEmailAddress" ' (length=58)
2 =>
array (size=1)
0 => string ' maxlength="60" ' (length=16)
3 =>
array (size=1)
0 => string '[email protected]' (length=21)
Upvotes: 2