Page 1 of 1

Replace all...

Posted: Wed Aug 16, 2006 12:31 am
by Mr Tech
I need to replace all the [linkid:#] on a page.

Basically, the script needs to extract the number (#) from the above code, and then needs to replace each [linkid:#] with a unique peice of code...

So for example this:

Code: Select all

Go to <a href="[linkid:4]">this page</a> or <a href="[linkid:19]">that page</a>... This [link:51] isn't inside a link...
Would end up like this:

Code: Select all

Go to <a href="page.php?id=4">this page</a> or <a href="page.php?id=19">that page</a>... This page.php?id=51 isn't inside a link...
How would I do that? Some code example would be good because I'm hopeless with regex...

Posted: Wed Aug 16, 2006 1:41 am
by RobertGonzalez
If you know the linkid will ways be numeric, try this

Code: Select all

$str = preg_replace('#\[linkid:([0-9]*)\]#', "<a href=\"page.php?id=1\">", $str);
Or for alphanumerics, try

Code: Select all

$str = preg_replace('#\[linkid:([A-Za-z0-9]*)\]#', "<a href=\"page.php?id=1\">", $str);
This is way untested...

Posted: Wed Aug 16, 2006 2:10 am
by Mr Tech
Thanks for that. It wasn't exactly what I wanted but atleast the regex was helpful... I figured otu what I want but the str_replace doesn't seem to be working... Any ideas?

Code: Select all

$match_count = preg_match_all("#\[linkid:([0-9]*)\]#si", $layout, $matches);
for ($i = 0; $i < $match_count; $i++) {	
	$linkid = $matches[1][$i];
	$linkid_info = mysql_fetch_array(mysql_query("select * from {$tbl_name}pages where id='$linkid'"));

	$layout = str_replace("[linkid:{$linkid}]", "index.php?page={$linkid_info[slug]}", $layout);
	$linkid = "";
}

Posted: Thu Aug 17, 2006 12:19 am
by Mr Tech
Is it really that difficult? Absolutley everything works except the str_replace part... Any ideas?

Posted: Thu Aug 17, 2006 3:41 am
by CoderGoblin
What happens when you do a print_r($matches) ?

You may find foreach to be better than a for loop.
In the SQL is linkid an integer or varchar column? If integer get rid of the quotes.

Code: Select all

$match_count = preg_match_all("#\[linkid:([0-9]*)\]#si", $layout, $matches);
if (!empty($matches[1])) {
   foreach($matches[1] as $linkid) {
         $linkid_info = mysql_fetch_array(mysql_query("select * from {$tbl_name}pages where id=$linkid"));
         $layout = str_replace("[linkid:{$linkid}]", "index.php?page={$linkid_info[slug]}", $layout);
   }
} else {
  echo("TEMP DEBUG No Matches");
}
This may work but not tested.