I'm trying to remove an input
tag that appears before a specific string. I have a huge string that's comprised of a form/table/tr/td/inputs, over 100 of them. Here's the sample html below:
<input type="hidden" name="special" value="123">
...
<tr>
<td>
<input type="checkbox" name="extendedeventinfo76022" value="y"> Enable Search
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="extendedeventinfo76006" value="y"> Enable Display
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="extendedeventinfo76137" checked value="y"> Enable Notes
</td>
</tr>
...
Let's say I want to remove the input tag for the Enable Display
. So far I can select the enable display, ^(.*?(\bEnable Display\b)[^$]*)$
but I'm not sure how to go to the previous tag <input...>
and remove it (or better yet, select the entire document, but excluding those inputs).
I also have lone input
tags that I'll have to remove as well based on what the name
attribute is. So basically, regex that will give the output below:
...
<tr>
<td>
<input type="checkbox" name="extendedeventinfo76022" value="y"> Enable Search
</td>
</tr>
<tr>
<td>
Enable Display
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="extendedeventinfo76137" checked value="y"> Enable Notes
</td>
</tr>
...
As you can see, the first hidden input with name "special" is gone as well as the input next to the words "Enable Display".
Designing a single regex to achieve what you want in one shot, is not quite trivial and will be slow to execute.
You might want to think about alternative approach - looping through the lines/tags (possibly using one of XML/HTML PHP parsers) and construct desired output accordingly to your criteria.
#!/usr/bin/php
<?php
$string = <<<'EOT'
<input type="hidden" name="special" value="123">
...
<tr>
<td>
<input type="checkbox" name="extendedeventinfo76022" value="y"> Enable Search
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="extendedeventinfo76006" value="y"> Enable Display
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="extendedeventinfo76137" checked value="y"> Enable Notes
</td>
</tr>
...
EOT;
echo preg_replace('/<input .* name="special" .*>|
<input .*>(?=\ Enable\ Display)/x', '', $string);