Reputation: 45
I want to use regular expressions to replace input tags with their corresponding values. The search must include the name of the input, since I have multiple inputs in the same form that need replacing.
For example, I need the following string:
<input value="Your Name" name="custom_field_1">
to become:
Your Name
My current code looks like this:
foreach ($_POST as $key => $value) {
if($key == 'post_id') continue;
$content = preg_replace("/<\s* input [^>]+ >/xi", htmlspecialchars($value), $content);
}
However, this will replace ALL inputs with the first value, so I need to refine the regex to include the name.
Thank you very much for your help!
Upvotes: 0
Views: 1119
Reputation:
This should work.
Just replace the match with $1
# (?s)<input(?=\s)(?>(?:(?<=\s)value\s*=\s*"([^"]+)"|".*?"|'.*?'|[^>]*?)+>)(?(1)|(?!))
(?s)
<input # Input tag
(?= \s )
(?> # Atomic grouping
(?:
(?<= \s )
value \s* = \s* # 'value' attribute
"
( # (1 start), 'value' data
[^"]+
) # (1 end)
"
| " .*? "
| ' .*? '
| [^>]*?
)+
>
)
(?(1) # Conditional - Only input tags with a 'value' attr
| (?!)
)
Sample:
<input type="hidden" value="Special:Search" name="title" />
Output:
** Grp 0 - ( pos 0 , len 59 )
<input type="hidden" value="Special:Search" name="title" />
** Grp 1 - ( pos 28 , len 14 )
Special:Search
Upvotes: 1
Reputation: 1230
You can match the whole string, capture the value by using parenthesis (..)
, making a capture group, and replacing the match with $1
- the first capture group.
<input value="(.+?)" name=".*?">
https://regex101.com/r/rH1wA2/3
Try:
preg_replace("<input value=\\"(.+?)\\" name=\\".*?\\">", $1, $str)
Note that this regex has "value", "name" and even spaces. If your strings sometimes look different, you have to take that to account and change the regex accordingly. <input value="(.+?)"[^>]*>
, for example, to replace no matter what follows your desired value.
Upvotes: 1