I need a php regular expression that replaces one tag with another

后端 未结 4 1209
广开言路
广开言路 2021-01-24 08:23

Here is what I need to be able to do:

I need to match the following tag:

text sample


        
相关标签:
4条回答
  • 2021-01-24 08:34

    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.

    0 讨论(0)
  • 2021-01-24 08:37

    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.

    0 讨论(0)
  • 2021-01-24 08:39

    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.

    0 讨论(0)
  • 2021-01-24 08:46

    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 ;)

    0 讨论(0)
提交回复
热议问题