T...">

Replacing the <a> tag with the <b> tag using PHP

Ok, I have a section of code with things like:
  <a title="title" href="http://example.com">Text</a>

I need to somehow reformat them so that they become:
  <b>Text</b>

At least 24 links changed, and they all have different headers and hrefs. Thanks in advance, Austin.

+3
source share
3 answers

Although this is not optimal, you can do it 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 the part of the line that has the form <a*>{TEXT}</a>, copy {TEXT}and replace this whole line with <b>{TEXT}</b>.

+14
source

Try it,

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

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

+2
source

, . href, :

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

The part between the first // searches for an opening tag (either <a> alone or with some parameters, in this case, free space \ s is required to avoid a match <abbrev> for example, for example), some text to be stored in brackets, and closing tag. The part between the second // is the replacement part, where \ 1 denotes the text matched by brackets in the first part.

See also the PHP function preg_replace . Then the final expression will look like this (verified):

preg_replace('/<a(?:\s[^>]*)?>([^<]+)<\/a>/i', '<b>\\1</b>', '<a href="blabla">Text</a>');
+1
source

Source: https://habr.com/ru/post/1796458/


All Articles