开发者

Changing a php "echoed" div attribute with php

开发者 https://www.devze.com 2022-12-23 15:18 出处:网络
I\'m using PHP to echo a content stored on my database.The content is a DIV carrying any type of data.

I'm using PHP to echo a content stored on my database. The content is a DIV carrying any type of data.

The problem is that I don't know the ID and I have some problems with these DIVs if I try to display them more than once.

So, the idea is to modify the DIV id each 开发者_运维技巧time I'd like to display them. Something like this:

<?php modify_div_id($data,"id-456"); ?>

How would I go about doing this?


This is ugly, but i think it works.

function modify_div_id( $data, $new_id ) {
  return preg_replace( '/(<div[^>]+?id=)("|\')(.*?)("|\')/i', '$1$2' . $new_id . '$4', $data );
}

The best way to go is to use an XML parser to change the attribute.

Edit: the function assumes the div to already have an id attribute.

Edit #2
It seems to be working!

jwandborg@sophie:~$ cat | php -r "eval( file_get_contents('php://stdin') );"
function modify_div_id( $data, $new_id ) {
  return preg_replace( '/(<div[^>]+?id=)("|\')(.*?)("|\')/i', '$1$2' . $new_id . '$4', $data );
}
echo modify_div_id('<div pajas="pajas" id="fisk">Innehåll</div>', 'nytt_id');

# Result: <div pajas="pajas" id="nytt_id">Innehåll</div>


Your question is worded kind of vague.

First off, the id attribute for HTML elements must be unique, so echoing a unique id is appropriate (you can also use a class).

If you've queried your database and received back, say, an array containing an id and the content, you can use the function as follows:

function modify_div_id($data, $id) {
  echo "<div id='$id'>$data</div>";
}

Just an example.

0

精彩评论

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

关注公众号