PHP - Replace Attributes By Tag Name
I have a site that allows members to create pages. These pages consist of small sections some of which HTML can be entered. To keep visitors from straying away from the site, any outside urls are brought up in a modal window. Using inline attributes, a class has to be created (or added to), and the title tag requires some special characters. I can probably get around this by inserting an onclick or something, but there must be a way to replace attributes, and I am at a loss.
The text segments are stored in a database. What I want to do is change the <a> tag attributes as the page is created. So I have a segment of text "$TheText" and I want to change or replace the attribute values. For instance, If $TheText contains an 'a' tag that looks like this: Code: [Select] <a class="MyClass" title="Godzilla" href="http://www.godzillaslair.com">Godzilla</a>I would want to change it to Code: [Select] <a class="MyClass Lightview" title="Godzilla :: {Lightview's parameters}">Godzilla</a>Or even just replace the attributes entirely, so it would look like Code: [Select] <a class="Lightview" title="{Inserted Title} :: {Lightview's parameters}">Godzilla</a> In other words, just replacing the attribute values. Of course, I need to see if the attributes exist. I know how to do that and how to get their values. But all that tells me is that I have an 'a' tag in the text with those values for those attributes. I cannot, for example, then do a str_replace in the first example, because there may be another tag in the text with the "MyClass" class. I can iterate character by character between <a and </a> but there must be a better way. I'm no good at regex, so I haven't even attempted that. Any suggestions would certainly be appreciated. Similar TutorialsThe situation is that I have a large string with some identifiers to say "replace me" with something else. My goal is to replace the values, but if one replacement includes one of the other keys, I don't want to replace it.
For example:
<?php $str = 'some blob ~abc~ followed by ~def~'; $arr_orig = array( '~abc~', '~def~' ); $arr_new = array( 'value~def~', 'blah' ); echo str_replace( $arr_orig, $arr_new, $str ); ?>This will echo: some blob valueblah followed by blah But that's not what I'm trying to accomplish. Basically, I want ~abc~ to be replaced with the literal: value~def~ and for the ~def~ that happens to be part of that string to NOT be replaced. I hope what I'm asking is clear. Basically, preg_replace/str_replace with arrays seems no different than just doing a FOR loop and replacing ~abc~ and then ~def~. But that's not what I need. I'm hoping that if ~abc~ is replaced with text that happens to be another identifier -- ~def~, ~xyz~, whatever -- that this already replaced text is not again replaced. Is there a built-in function to do something like this? If not, should I just parse the whole string and count characters or something? Seems like a pain (and slow!) Hi i wrote a find and replace code but my code replace last value of array and skip the first, second.... values in the array. Please give me an idea because i stack with this code. Regards $KeyWord = explode("\n", $RowGetWords['KEYWORDS']); $Replace = explode("\n", $RowGetWords['ReplaceTo']); for($i=0; $i<count($KeyWord); $i++){ $pattern = $KeyWord[$i]; $replace = "<a href=\"" .$URL. "\" target=\"_blank\" >" .$Replace[$i]. "</a>"; $html = str_replace($pattern, $replace, $Row['MessageBody']); } $_POST['select'] permits me access to the selected value of my combo box named 'select'. are any other attributes of the box accessible? in particular, index # ... etc.? thanks in advance for any light you might shed on the topic. I cant get my head around this. I m trying to add product attributes into this script. I have products tables and product_extras product.id and product_extras.id are same. How can I add this to cart. Is there any easy way to do this. Any help would be much appreciated! Quote cart.php Code: [Select] <?php // Include MySQL class require_once('inc/mysql.class.php'); // Include database connection require_once('inc/global.inc.php'); // Include functions require_once('inc/functions.inc.php'); // Start the session session_start(); // Process actions $cart = $_SESSION['cart']; $action = $_GET['action']; switch ($action) { case 'add': if ($cart) { $cart .= ','.$_GET['id']; } else { $cart = $_GET['id']; } break; case 'delete': if ($cart) { $items = explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($_GET['id'] != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } $cart = $newcart; } break; case 'update': if ($cart) { $newcart = ''; foreach ($_POST as $key=>$value) { if (stristr($key,'qty')) { $id = str_replace('qty','',$key); $items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($id != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } for ($i=1;$i<=$value;$i++) { if ($newcart != '') { $newcart .= ','.$id; } else { $newcart = $id; } } } } } $cart = $newcart; break; } $_SESSION['cart'] = $cart; ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>products</title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <div id="shoppingcart"> <h1>Your Shopping Cart</h1> <?php echo writeShoppingCart(); ?> </div> <div id="contents"> <h1>Please check quantities...</h1> <?php echo showCart(); ?> <p><a href="index.php">Back to products...</a></p> </div> </body> </html> Quote functions.php Code: [Select] <?php function writeShoppingCart() { $cart = $_SESSION['cart']; if (!$cart) { return '<p>You have no items in your shopping cart</p>'; } else { // Parse the cart session variable $items = explode(',',$cart); $s = (count($items) > 1) ? 's':''; return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>'; } } function showCart() { global $db; $cart = $_SESSION['cart']; if ($cart) { $items = explode(',',$cart); $contents = array(); foreach ($items as $item) { $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1; } $output[] = '<form action="cart.php?action=update" method="post" id="cart">'; $output[] = '<table>'; foreach ($contents as $id=>$qty) { $sql = 'SELECT * FROM products WHERE id = '.$id; $result = $db->query($sql); $row = $result->fetch(); extract($row); $output[] = '<tr>'; $output[] = '<td><a href="cart.php?action=delete&id='.$id.'" class="r">Remove</a></td>'; $output[] = '<td>'.$title.'</td>'; $output[] = '<td>£'.$price.'</td>'; $output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>'; $output[] = '<td>£'.($price * $qty).'</td>'; $total += $price * $qty; $output[] = '</tr>'; } $output[] = '</table>'; $output[] = '<p>Grand total: <strong>£'.$total.'</strong></p>'; $output[] = '<div><button type="submit">Update cart</button></div>'; $output[] = '</form>'; } else { $output[] = '<p>You shopping cart is empty.</p>'; } return join('',$output); } ?> Context. Class AbstractTenantEntity's purpose is to restrict access to data to the tenant (i.e. account, owner, etc) that owns the data. Any entity which extends it will have the TenantId added when created and the TenantId in the WHERE clause for all other requests. Tenant typically does not have collections of the various entities which extend AbstractTenantEntity, but does for a few of them do. When using annotation, I handled it by applying Doctrine's AssociationOverride annotation to the extended classes which should have a collection in Tenant. use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity() */ class Tenant { /** * @ORM\OneToMany(targetEntity=Asset::class, mappedBy="tenant") */ private $assets; // Other properties and typical getters and setters }
use Doctrine\ORM\Mapping as ORM; abstract class AbstractTenantEntity implements TenantInterface { /** * inversedBy performed in child where required * @ORM\ManyToOne(targetEntity=Tenant::class) * @ORM\JoinColumn(nullable=false) */ protected ?Tenant $tenant = null; // Typical getters and setters }
use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity() * @ORM\AssociationOverrides({ * @ORM\AssociationOverride(name="tenant", inversedBy="assets") * }) */ class Asset extends PublicIdTenantEntity { // Various properties and typical getters and setters }
So, now I am changing from annotations to attributes, and modified AbstractTenantEntity as follows: use Doctrine\ORM\Mapping\ManyToOne; use Doctrine\ORM\Mapping\JoinColumn; abstract class AbstractTenantEntity implements TenantInterface { /** * inversedBy performed in child where required */ #[ManyToOne(targetEntity: Tenant::class)] #[JoinColumn(nullable: false)] protected ?Tenant $tenant = null; // Typical getters and setters } Next I went to modify Asset and realized that there didn't appear to be an attribute for AssociationOverride. I found a little discussion on the topic on github but couldn't find any resolution. Question Can inheritance be used with PHP 8 attributes where the property is defined in the parent class and the attribute is applied in the child class? Googling php 8 attributes inheritance didn't provide anything and thus I expect the answer is no but thought I'd ask. Thanks
EDIT. Maybe Doctrine does have an attribute version: https://github.com/doctrine/orm/blob/2.9.x/lib/Doctrine/ORM/Mapping/AttributeOverride.php EDIT2. Actually don't think so Edited July 30 by NotionCommotionHi, Im trying to grab some data from a XML generated by an external server. I know how to grab from XML without attributes, but I cant seem to wrap my head around the structure of this file. What would be easiest way to get the value of the "dbnr" field? Part of the XML file: Code: [Select] <data> <location> <field name="id" format="Long">xxxxxx</field> <field name="dbnr" format="Long">xxxxxx</field> <field name="jobnr" format="Long">xxxxxx</field> <field name="job_type" format="String" maxlen="50">xxxxxx</field> <field name="job_category" format="String" maxlen="50">xxxxxx</field> </location> </data> Hi all, I'm sure I'm making this far more difficult than I need to... I've got an xml document... <library id="1"> <lname>Lib1</name> <book id="1"> <title>book 1</title> <author>Author 1</author> </book> <book id="2"> <title>book 2</title> <author>Author 2</author> </book> </library> I can access the nested elements using xpath like : $result = $xml->xpath('//book'); foreach($result as $books) { echo $books->title; } How would I do this for the attributes? If I specify I want the attributes in the xpath query I can't get at the elements... I'm trying to turn this xml file into a simple relational database... A library table and a book table. So I need the library id (attribute) and the name(nested element) for one insert query - and the book id, title, author and the library id for the other. Anyone got any idea? Cheers John I am making a project by designing my own MVC model. In this the user accesses controller class which further calls model class which accesses the database by $dbh attiribute defined public. My View is a script which calls different pages. In the constructor of model I'm establishing connection with the database. Firstly I construct the model object when the user accesses i.e. in the controller class to check in the databse then if the username is not present in the dtaabse I want to insert his info in the database for that I again calla model class but this time I again have to establish connection. Is the $dbh firstly constructed is lost like dangling pointers in C++. Do I have to worry about it. If yes how can I solve this problem. Hi, I am new to xml parsing and I just want to know how to check whether a node has attributes: Here is my xml file to use: ================= Code: [Select] <?xml version="1.0" encoding="ISO-8859-1"?> <email> <message> <to> <toFirstName>Tove</toFirstName> <toLastName toType="common" style="swag">Smith</toLastName> </to> <from> <fromFirstName>Jani</fromFirstName> <fromLastName fromType="unique">Dravison</fromLastName> </from> <heading>Reminder</heading> <body> <prologue>Tis the night before Xmas...</prologue> <paragraph1>Don't forget me this weekend!</paragraph1> <paragraph2>Jump the gun!</paragraph2> <epilogue>The end of the world.</epilogue> </body> </message> <message> <to>employees</to> <from>CEO</from> <heading>Power Lunch</heading> <body> <prologue></prologue> <paragraph1>Year over year data</paragraph1> <paragraph2>Downsizing</paragraph2> <epilogue>The end.</epilogue> </body> </message> </email> Here the simple script that I cannot get to work: ================================== Code: [Select] <?php $simpleXMLObj=simplexml_load_file("email.xml"); if($simpleXMLObj->to[0]->toLastName[0]->attributes()->getName) print "YES: this node has attributes!"; else print "NO:"; ?> Please I really need help, it is simple I know but I am new to xml parsing and mixed up. How can I print the attributes of a child node? I have been trying and looking and cant get it. I need the attributes of subfield printed after datafield so a line would look like datafield plus attributes plus subfield attributes plus subfield =906 __$a0$bcbc$corignew etc... <?php //child nodes http://www.w3schools.com/php/php_xml_dom.asp //http://books.google.com/books?id=ygQRKDEsLecC&pg=PA196&lpg=PA196&dq=print+php+xml+child+node+attributes&source=bl&ots=TCAhH4kpCt&sig=yJUPXesIkRUrNXdNE9Yr5ul7Wdw&hl=en&ei=U51kTeKQKsL48AbN4MDTBg&sa=X&oi=book_result&ct=result&resnum=10&ved=0CF4Q6AEwCQ#v=onepage&q=print%20php%20xml%20child%20node%20attributes&f=false //http://stackoverflow.com/questions/4598409/printing-content-of-a-xml-file-using-xml-dom $doc = new DOMDocument(); $doc->preserveWhiteSpace = FALSE; $doc->load( 'loc.xml' ); $root = $doc->documentElement; $type = $root->nodeType; //print $doc->nodeName."\n"; //print $root->nodeName."\n"; //print $doc->nodeValue."\n"; //print $root->nodeValue."\n"; $librecords = $doc->getElementsByTagName( "record" ); foreach( $librecords as $record ){ $leader = $record->getElementsByTagName( "leader" ); $controlfields = $record->getElementsByTagName( "controlfield" ); $datafields = $record->getElementsByTagName( "datafield" ); $subfields = $record->getElementsByTagName( "subfield" ); $leader = $leader->item(0)->nodeValue; echo '=LDR '.$leader.'<BR>'; foreach( $controlfields as $controlfield ){ $tag = $controlfield->getAttribute('tag'); $cf_value = $controlfield->firstChild->nodeValue; echo "=".$tag." ".$cf_value.'<BR>'; } foreach( $datafields as $datafield ){ $tag = $datafield->getAttribute('tag'); $ind1 = $datafield->getAttribute('ind1'); $ind2 = $datafield->getAttribute('ind2'); if ($ind1 ==" ") {$ind1 = "_";} if ($ind2 ==" ") {$ind2 = "_";} echo "=".$tag." ".$ind1.$ind2; //if($datafield->hasChildNodes()){echo 'This node has children!<br />';} foreach ($datafield->childNodes AS $item) { // $arr = $item->attributes; print $arr; print 'nodeName '.$item->nodeName . " = " . $item->nodeValue." | " ;} //. "<br />"; } // foreach ($datafield->children() as $node) { // $arr = $node->attributes(); // returns an array // print ("code=".$arr["code"]); // get the value of this attribute // print (" Company=".$node->subfield); // print ("<p><hr>"); //} // foreach( $subfields as $subfield){ // foreach($subfield->attributes as $attr){ // $attributes = $subfield->attributes; // print $attr->nodeName; // print $attr->nodeValue; // //print $attributes->nodeName; //print $attributes->nodeValue; // print $subfield->nodeName; // print $subfield->nodeValue; //}} // print $item->nodeValue ; // print $item->attributes("code"); // $valueID = $item->getAttribute('code'); // print $item->nodeName->attributes("code"); // echo $item->nodeValue.getAttribute("code"); // print $item->getAttribute('code') //http://www.devshed.com/c/a/PHP/Accessing-Attributes-and-Cloning-Nodes-with-the-DOM-XML-Extension-in-PHP-5/1/ echo '<BR>'; } foreach( $subfields as $subfield ){ $code = $subfield->getAttribute('code'); $sf_value = $subfield->firstChild->nodeValue; echo '$'.$code.$sf_value.'<BR>'; } echo '<BR>'; } ?> Code: [Select] <leader>01026ngm a22002773a 4500</leader> <controlfield tag="001">16429180</controlfield> <controlfield tag="005">20100823131409.0</controlfield> <controlfield tag="007">vffcjaho|</controlfield> <controlfield tag="008">100823s2010 xxu060 mleng </controlfield> <datafield tag="906" ind1=" " ind2=" "> <subfield code="a">0</subfield> <subfield code="b">cbc</subfield> <subfield code="c">orignew</subfield> <subfield code="d">u</subfield> <subfield code="e">ncip</subfield> <subfield code="f">20</subfield> <subfield code="g">y-movingim</subfield> </datafield> <datafield tag="955" ind1=" " ind2=" "> <subfield code="b">qm12 2010-08-23</subfield> </datafield> I have the following code below: <league name="italy" id="1"> <match name="AC Milan v Palermo" time="15/02/2011 20:45"> <bettype name="Versus (with Draw)"> <bet outcome_name="AC Milan" odd="1.87"> <bet outcome_name="X" odd="3.40"> <bet outcome_name="Palermo" odd="4.00"> </bettype> </match> <match name="Juventus v Torino" time="15/02/2011 20:45"> <bettype name="Versus (with Draw)"> <bet outcome_name="Juventus" odd="2.00"> <bet outcome_name="X" odd="3.00"> <bet outcome_name="Torino" odd="2.00"> </bettype> <bettype name="Half Time"> <bet outcome_name="1" odd="2.40"> <bet outcome_name="X" odd="3.40"> <bet outcome_name="2" odd="1.40"> </bettype> </match> </league> <league name="Spain" id="2"> <match name="Barcelona v Real Madrid" time="15/03/2011 21:45"> <bettype name="Versus (with Draw)"> <bet outcome_name="Barcelona" odd="1.87"> <bet outcome_name="X" odd="3.40"> <bet outcome_name="Real Madrid" odd="4.00"> </bettype> </match> </league> im trying to parse attributes of above xml with using xpath functions. what i want to output is this: ( <bettype name="Half Time"> this will be ignored ) Italy AC Milan v Palermo 1.87 3.40 4.00 Juventus v Torino 2.00 3.00 2.00 spain Barcelona v Real Madrid 1.87 3.40 4.00 im trying do this with below xpath codes $xml=simplexml_load_file('http://xml.gamebookers.com/sports/football.xml_attr.xml'); $league=$xml->xpath("//league"); $matches=$xml->xpath('//bettype[@name="Versus (with Draw)"]/..'); $odds=$xml->xpath('//match/bettype[@name="Versus (with Draw)"]/bet'); i searched and tried lots of tutorials. i need help in writing the correct code thanks The following script came from using-custom-paths. It appears that these are PHP 8's new attributes, correct? <?php // api/src/Entity/Question.php #[ApiResource( subresourceOperations: [ 'api_questions_answer_get_subresource' => [ 'method' => 'GET', 'path' => '/questions/{id}/all-answers', ], ], )] class Question { }
I currently am using PHP7 and will need to convert them. Does the following look correct? Thanks /** * @ApiResource( * subresourceOperations = { * "api_questions_answer_get_subresource" = { * "method" = "GET", * "path" = "/questions/{id}/all-answers" * } * } * ) */
Hi, I have been trying to improve my PHP programming skills by following the Lynda.com Beyond the basics tutorial and they came to a section where they were building common database methods inside a database class. Since they did not have PHP 5.3 (Where late static bindings is introduced) they had to place code referring to self:: inside of each class that needs this functionality. It seems that not having late static binding was binding self to the database class and not to other classes that call it statically. I will insert some code to explain this better. Long story short, I was really interesting in getting an attributes function working and as I do not have late static bindg either, I cannot figure out how to call it from inside a class to make it function correctly. Here is some code. Below is the attribute class they wrote. Each class declared an array of attributes for each of the classes that want to call this method like protected static $db_fields = array('id', 'email', 'password', 'etc'); Code: [Select] protected function attributes() { // return an array of attribute names and their values $attributes = array(); foreach(self::$db_fields as $field) { if(property_exists($this, $field)) { $attributes[$field] = $this->$field; } } return $attributes; } They planned on moving this code to a DatabaseObject class after they get LSB but until then, have to include it in every class that wants use this. Is there any way to write this as a function, include it in a class, and call the method without late static binding.. or even place this inside a database class and call it from another class without LSB? Forgive me if I am not explaining this correctly, again, I am still learning. My version of PHP is 5.2.6. I am trying to write a more elegant solution to be able to check an object, find only the properties in an object that have values, and update those values in a database with a matching ID. I am extending a class from a generic user class here is an example of my code Code: [Select] <?php require_once('User.php'); require_once('Database.php'); class Vendor extends User { protected static $vendor_attributes = array('id', 'nothing' , 'tagline' , 'bio'); protected static $table_name = "user_vendors"; public $tagline; }//close class ?> Okay, the title may sound a little confusing but it's the best way I could explain it. I think it's better to understand what I'm doing by looking at my function below: <? function refresh($name,$num,$time) {?> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> update<?=$num?>(); function update<?=$num?>() { num = Math.random(); $('span.<?=$name?>').load('refresh.php?a=<?=$name?>'); setTimeout('update<?=$num?>()', <?=$time?>/1000); } </script> }<? //refresh('name of span tag','JS update#', 'refresh time'); refresh('spantag1','1', '5'); refresh('spantag2,'2', '5'); refresh('spantag3','3', '5'); ?> As you can see this would output 3 javascript codes on the page. I'd then use the span tag to allow this to refresh every 5 seconds like below: <span class=spantag1>This contains the contents that will refresh in span tag one</span> to refresh every 5 seconds. This is a huge problem because I have about 50 tags that need to be refreshed every 'x' seconds. Because of using all these 50 refreshes my page size is 1.36MB large Without all this javascript my page size is only 38KB. I'm wanting to use one javascript code but allow up to 50+ raw data that is inside the span tag to be refreshed. <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> update<?=$num?>(); function update<?=$num?>() { num = Math.random(); $('span.<?=$name?>').load('refresh.php?a=<?=json_encode($arr)?><?=$name?>'); setTimeout('update<?=$num?>()', <?=$time?>); } </script> Sorry if it didn't make sense, tried my best lol. Thanks and all help is much appreciated. User can edit a post. I need to replace the html '<br/>' element to newline character ('\n') . When a user will edit a post he/she will not see the '<br/>'. How can i do this with php ? ok so I have an string with data that I need to be replaced with contents from an array. I need the occurance position replace with the index of the array. example Code: [Select] //here is the setup $string = "testing %s one %d %s"; array('this',1,'three'); //here is the result testing this one 2 three the problem I am having is because the %s can occur more than once I cant use str_replace. I am working on a solution with substr_replace but was wondering if anyone had any suggestions on how to do this. When I replace it I also need to run the value through a function so keep that in mind. Also the replace's are stored in an array so they need to be looped through as well. Code: [Select] $replaces = array('%s'=>'func_one','%d'=>'func_two'); Any help is appreciated. How does wordpress and other similar CMS/applications replace their div elements? For example, if you view the source code of a wordpress site, you will only see: Quote <div id="header"></div> Where, the above code is clearing being switched out for "header.php". How is this done? I believe it's php and jquery, but I would be wrong. Thanks! Hello, I'm trying to convert a paragraph of text which is already html formatted. I wish to find keywords, such as, 'PHP', which are contained in the paragraph, and replace them with a link, for example <a href="http:/www...">PHP</a> str_replace('PHP', '<A href=""....">PHP</a>', $content); My problem arises when some of these keywords are already contained in a link, so say, visit PHP website, is all one link, so str_replace would simply convert the PHP in this string, to two links for one single word. Code: [Select] <a href="">visit <A href=""....">PHP</a> website</a>How could this problem be resolved? Thanks |