0

I have a variable which consists of diffrent html tags:

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

I want to find all the u tags in the $html variable and give them the id of their contents.

It should return:

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

3 Answers3

1

You can use preg_replace() if you want it fast way, or learn about DOMDocument if you want to do it the proper way.

$pattern = '~<u>([^<]*)</u>~Ui';
$replace = '<u id="$1">$1</u>';
$html = preg_replace($pattern, $replace, $html);
Forien
  • 2,712
  • 2
  • 13
  • 30
  • OP wants the id's in lower case, yours are in upper case! – Rizier123 Mar 26 '15 at 12:52
  • @Rizier123 In HTML, attributes' values are case insensitive. Same goes for CSS selectors. – Forien Mar 26 '15 at 13:02
  • 1
    `
    sdfsdf
    sdfsdf
    ` See the difference ? See also: http://stackoverflow.com/a/7559251/3933332 And id is a selector!
    – Rizier123 Mar 26 '15 at 13:04
  • 1
    @Rizier123 I see you spam without even testing. What you posted here is just proof to statement of mine - `id`s and CSS selectiors are **case insensitive** – Forien Mar 26 '15 at 13:06
  • ^ Copy my example and say me if both div's has a black background? – Rizier123 Mar 26 '15 at 13:08
  • ^ Did you read my posted SO answer related to this and read the CSS recommendation ? Here you have the link directly to it: http://www.w3.org/TR/1999/REC-html401-19991224/struct/global.html#adef-id – Rizier123 Mar 26 '15 at 13:12
0

You can use preg_replace.

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

The e means "evaluate", which allows you to cram the "strtolower" command into the replacement.

kainaw
  • 4,256
  • 1
  • 18
  • 38
0

it will be good to do it using jquery if it suits your need else Forien answer is good to go

here it goes to do it in jquery

your html

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

your js

<script type="text/javascript">
     $('#specialString > ul').each(function() {
        $(this).attr('id', $(this).text());
    });
</script>
Kuldeep Dangi
  • 4,126
  • 5
  • 33
  • 56