开发者

create anchors in a page with the content of <h2></h2> in PHP

开发者 https://www.devze.com 2023-01-05 01:22 出处:网络
Well I have a html text string in a variable: $html = \"<h1>title</h1><h2>subtitle 1</h2> <h2>subtitle 2</h2>\";

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开发者_C百科 browser and also get the subtitles as an array.

I think is using regex.. please help.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消