tags:

views:

46

answers:

1

Well I have a html text string in a variable:

$html = "<h1>title</h1><h2>subtitle 1</h2> <h2>subtitle 2</h2>";

so I want to create anchors in each subtitle that has with the same name and then print the html code to browser and also get the subtitles as an array.

I think is using regex.. please help.

+1  A: 

I think this will do the trick for you:

$pattern = "|<h2>(.*)</h2>|U";
preg_match_all($pattern,$html,$matches);

foreach($matches[1] as $match)
    $html = str_replace($match, "<a name='".$match."' />".$match, $html);

$array_of_elements = $matches[1];

Just make sure that $html has the existing html before this code starts. Then it will have an <a name='foo' /> added after this completes, and $array_of_elements will have the array of matching text values.

JGB146