Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

php

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

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

There are at least 24 links being changed, and they all have different titles and hrefs. Thanks in advance, Austin.

like image 701
Austin Peterson Avatar asked Mar 05 '11 07:03

Austin Peterson


2 Answers

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>.

like image 89
shmeeps Avatar answered Nov 15 '22 02:11

shmeeps


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.

like image 25
Odyss3us Avatar answered Nov 15 '22 03:11

Odyss3us