I'm using PHP and MySQL. Imagine a series of articles that all include the following HTML code:
</div>
<div id="Homes">
<h2>Homes</h2>
However, there could be differences in whitespace, like this:
</div>
[WHITESPACE]
<div id="Homes"><h2>Homes</h2>
I'd like to know if it's possible to use regular expressions to insert something before the first div closing tag in the example above, like this:
[INSERT SOMETHING HERE]
</div>
<div id="Homes">
<h2>Homes</h2
The regular expression would ignore whitespace and target the last div closing tag before div#Homes.
If you don't know the exact regular expression that would do this, that's fine. I just need to know if it can be done (and whether it can be done with phpMyAdmin or if I need a different program).
If it CANNOT be done, then I'm going to have to insert some code that can be replaced with str_replace. But it would be a lot simpler and cleaner if I could use regular expressions.
PS My page will actually include several similar divs/headings - Homes, Ecology, Environment, etc. I'd like to be able to insert content or features at the end of each section - but before the closing div tag in some cases.
You can use the following regex:
</div>(?=[\s\n\r]+<div id="Homes">)
Then replace with
[INSERT SOMETHING HERE]\n</div>
This will match the last </div>
before the Homes div, not matter the number of newlines or whitespaces.
</div>
<div id="Homes">
<h2>Homes</h2>
Explanation of regex:
</div>
match the </div>
?=
is a forward lookup. Note that this is non capturing, and it will not be part of the match [\\s\\n\\r]
match a whitespace or newline character If you also want to match when everything is on one line then you would just replace +
with *
:
</div>(?=[\s\n\r]*<div id="Homes">)
matches the <\\div>
in
</div><div id="Homes"><h2>Homes</h2><div id="Homes">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.