Jump to content

Help with string replace


everisk

Recommended Posts

Hi,

 

I have to add <div class="overlayON"><?php graph($i); ?></div> in front of all <a href="..">. The value of $i is dynamic.

I thought that str_replace would do the job but seem like I cannot use dynamic variable to replace the string.

 

To make it clearer ..

<div class="overlayON"><?php graph(1);?></div><a href=....>

<div class="overlayON"><?php graph(2);?></div><a href=....>

<div class="overlayON"><?php graph(3);?></div><a href=....>

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/62618-help-with-string-replace/
Share on other sites

Sorry .. here it is. Thanks a lot!

 

<?php

$url = "http://wisetarget.net/promotions/sony/issue-MySony060July17/mysony/index_th.php"; 
$input = @file_get_contents($url) or die('Could not access file: $url');

////first I try to extract the link from href tag by regular expressions
$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>"; 
if(preg_match_all("/$regexp/siU", $input, $matches)) 
{ 
print "<pre>";
print_r ($matches);
print "</pre>";
}


$replace = "<div class=\"overlayON\">";
$replace .= graph($matches['2']['0']); // this number has to loop to [2][1] , [2][2], and so on for all $matches value
$replace .= "</div><a";

$html = str_replace("<a", $replace, $input);

print $html;


function graph($var) {
$var .= "CORRECT";
return $var;
}

?>

What is the intention of the double ?? and the *? in your regexp?  I tried your regexp without and I get this:

 

$regexp = "<a\s[^>]*href=(\"?)([^\" >]*)\\1[^>]*>(.*)<\/a>";
$str = "<a href=\"blah.html\"></a>";
print "<pre>";
if (preg_match("|$regexp|", $str, &$matches)) {
  var_dump($matches);
}

 

Output:

array(4) {
  [0]=>
  string(24) "<a href="blah.html"></a>"
  [1]=>
  string(1) """
  [2]=>
  string(9) "blah.html"
  [3]=>
  string(0) ""
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.