php - Regex replacing HTML strings? -


this string:

<ol>     <li>         <a rel="nofollow" href="http://127.0.0.1/index.php/something?price=3%2c25"><span class="price">50,00€</span> - <span class="price">75,00€</span></a> (38)     </li>     <li>         <a rel="nofollow" href="http://127.0.0.1/index.php/something?price=4%2c25"><span class="price">75,00€</span> - <span class="price">100,00€</span></a> (11)     </li> </ol> 

i want replace

<span class="price">50,00€</span> - <span class="price">75,00€</span> 

with "foobar" ,

<span class="price">75,00€</span> - <span class="price">100,00€</span> 

with "foobar2" example. way know line replace what, price=3 or price=4 part in url.

so after replacement, string should like:

<ol>     <li>         <a rel="nofollow" href="http://127.0.0.1/index.php/something?price=3%2c25">foobar</a> (38)     </li>     <li>         <a rel="nofollow" href="http://127.0.0.1/index.php/something?price=4%2c25">foobar2</a> (11)     </li> </ol> 

i tried preg_replace, gets of string. ideas?

thanks helping!

if wanting change contents, based on sort of key, recommend using array hold values.

<?php  $foo_array = array(3 => 'foobar', 4 => 'foobar2'); 

now, i'm adding in original string have operate on:

$string = '<ol>     <li>         <a rel="nofollow" href="http://127.0.0.1/index.php/something?price=3%2c25"><span class="price">50,00€</span> - <span class="price">75,00€</span></a> (38)     </li>     <li>         <a rel="nofollow" href="http://127.0.0.1/index.php/something?price=4%2c25"><span class="price">75,00€</span> - <span class="price">100,00€</span></a> (11)     </li> </ol>'; 

then, can use replace on string.

$new_string = preg_replace_callback('/(price=(3|4)([a-z0-9%]+)">)(.*?)(<\/a>)/ms', function ($m) use ($foo_array) {return "$m[1]".$foo_array[$m[2]]."$m[5]";}, $string);  print $new_string; 

alternatively, if you'd heed marc b's advice in comments, can use php's dom manipulations work. not expert in this, took stab @ , seems output same regex solution above (except adds doctype, html , body headers in):

$dom_document = new domdocument(); // create new document $dom_document->loadhtml($string); // load string document $links = $dom_document->getelementsbytagname('a'); // pull out links out of document  // loop through each link foreach ($links $link) {      // if find 3 or 4 after price=, then, replace text of      // - link (the nodevalue) item array     if (preg_match('/price=(3|4)/ms', $link->getattribute('href'), $m)) {         $link->nodevalue = $foo_array[$m[1]];     }  }  $new_string_2 = $dom_document->savehtml(); // write changes string  print $new_string_2; 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -