Replacing tag with tag using PHP

前端 未结 4 1275
无人及你
无人及你 2020-12-17 03:09

OK, I have a section of code with things like:
Text

I need to reformat thes

相关标签:
4条回答
  • 2020-12-17 03:32

    Try this,

    $link = '<a title="title" href="http://example.com">Text</a>';
    echo $formatted = "<b>".strip_tags($link)."</b>";
    

    Check this link out as well, I think this is what you are looking for.

    0 讨论(0)
  • 2020-12-17 03:33

    You want to read about Regular Expressions because you will need them sooner or later anyway. If you do not mind about the content of the href property, then you can use:

    s/<a(?:\s[^>]*)?>([^<]+)<\/a>/<b>\1<\/b>/
    

    The part between the first // searches for the opening tag (either <a> alone or with some parameters, in this case a white space \s is required to avoid matching <abbrev> e.g. as well), some text which will stored by the brackets, and the closing tag. The part between the second // is the replacement part where \1 denotes the text matched by the brackets in the first part.

    See also PHP’s preg_replace function. The final expression would then look like this (tested):

    preg_replace('/<a(?:\s[^>]*)?>([^<]+)<\/a>/i', '<b>\\1</b>', '<a href="blabla">Text</a>');
    
    0 讨论(0)
  • 2020-12-17 03:40

    To replace a tag by another and matching / replacing attributes names at the same time :

    $string = '<img src="https://example.com/img.png" alt="Alternative"/>';
    $string = preg_replace('/<img src="(.+?)" alt="(.+?)"\\/>/is','<amp-img src="$1" alt="$2"></amp-img>',$string);
    //$string is now '<amp-img src="https://example.com/img.png" alt="Alternative"></amp-img>'
    
    0 讨论(0)
  • 2020-12-17 03:43

    Although not optimal, you can do this with regular expressions:

    $string = '<a title="title" href="http://example.com">Text</a>';
    
    $string = preg_replace("/<a\s(.+?)>(.+?)<\/a>/is", "<b>$2</b>", $string);
    
    echo($string);
    

    This essentially says, look for a part of the string that has the form <a*>{TEXT}</a>, copy the {TEXT}, and replace that whole matched string with <b>{TEXT}</b>.

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