问题
Here is what I need to be able to do:
I need to match the following tag:
<SPAN style="TEXT-DECORATION: underline">text sample</SPAN>
I need to replace the span with an html3 compliant tag, but keep the text in between. The final tag should look like this after replacement:
<u>text sample</u>
I'm just not good with regular expressions and can't seem to come up with the answer.
Thank you in advance.
回答1:
Regular expressions are not designed for tag manipulation.
If you have any form of nesting going on, it gets messy.
However, given the very simple example provided you could perhaps do this:
$MyString = preg_replace
( '/(?si)<SPAN\s+style\s*=\s*"TEXT-DECORATION:\s*underline;?"\s*>(.*?)<\/SPAN>/'
, '<u>$1</u>'
, $MyString
);
But this is flawed in many ways, and you are much better off using a tool designed for manipulating tags instead.
Have a look at DOMDocument->loadHTML() and related functions.
回答2:
DO NOT USE REGULAR EXPRESSIONS TO PARSE HTML
do not use regular expressions to parse HTML
do not use regular expressions to parse HTML
do not use regular expressions to parse HTML
do not use regular expressions to parse HTML
do not use regular expressions to parse HTML
do you need more clarification?
Use DomDocument::LoadFromHTML ;)
回答3:
You'll need several lines like this:
preg_replace('|<SPAN style="TEXT-DECORATION: underline">(.+?)</SPAN>|', '<u>$1</u>', $text);
preg_replace('|<SPAN style="FONT-WEIGHT: bold">(.+?)</SPAN>|', '<b>$1</b>', $text);
preg_replace('|<SPAN style="FONT-STYLE: italic">(.+?)</SPAN>|', '<i>$1</i>', $text);
etc. Although if there's any possibility that the tags won't exactly match those regular expressions (which is usually the case, except for very simple machine-generated HTML), doing this with regular expressions becomes fiendishly complicated, and you'd be better off using a parser of some kind.
回答4:
For the basic example that you've given.
<?php
$string = '<SPAN style="TEXT-DECORATION: underline">text sample</SPAN>';
$pattern = '/<SPAN style=\"TEXT-DECORATION: underline\">(.+?)<\/SPAN>/';
$replacement = '<u>$1</u>'
echo preg_replace($pattern,$replacement,$string);
?>
will do the trick. The pattern regex is quite easy - it's exactly what you're looking for (with quotes and '/' escaped) with a (.+?) which says to include all possible characters until the close of the SPAN tag. This assumes that you're code is consistently formatted, you could append a 'i' to the end of $pattern to make it case-insensitive.
Note that this isn't really the right way of doing it.
来源:https://stackoverflow.com/questions/584085/i-need-a-php-regular-expression-that-replaces-one-tag-with-another