Replace all...

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Replace all...

Post 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...
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post 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...
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Post 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 = "";
}
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Post by Mr Tech »

Is it really that difficult? Absolutley everything works except the str_replace part... Any ideas?
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post 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.
Post Reply