PHP给出其内容的标记id


PHP give tag id of its contents

我有一个变量,它由不同的html标签组成:

$html = '<h1>Title</h1><u>Header</u><h2>Sub Title</h2><p>content</p><u>Footer</u>'

我想在$html变量中找到所有的u标记,并给它们内容的id。

它应该返回:

$html = '<h1>Title</h1><u id="header" >Header</u><h2>Sub Title</h2><p>content</p><u id="footer" >Footer</u>'

如果你想快速使用preg_replace(),或者如果你想以正确的方式使用DOMDocument,你可以学习它。

$pattern = '~<u>([^<]*)</u>~Ui';
$replace = '<u id="$1">$1</u>';
$html = preg_replace($pattern, $replace, $html);

您可以使用preg_replace。

$html = preg_replace('~<u>([^<]+)</u>~e','"<u id='"".strtolower("$1")."'" >$1</u>"', $html);

e的意思是"评估",它允许您将"strtolower"命令填充到替换中。

如果jquery适合您的需求,那么使用它会很好,否则Forien的答案是使用

here it goes to do it in jquery

你的html

<div id='specialString'>
    <h1>Title</h1><u>Header</u><h2>Sub Title</h2><p>content</p><u>Footer</u>
</div>

你的js

<script type="text/javascript">
     $('#specialString > ul').each(function() {
        $(this).attr('id', $(this).text());
    });
</script>