Any questions involving matching text strings to patterns - the pattern is called a "regular expression."
Moderator: General Moderators
Mr Tech
Forum Contributor
Posts: 424 Joined: Tue Aug 10, 2004 3:08 am
Post
by Mr Tech » Wed Aug 16, 2006 12:31 am
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...
RobertGonzalez
Site Administrator
Posts: 14293 Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA
Post
by RobertGonzalez » Wed Aug 16, 2006 1:41 am
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...
Mr Tech
Forum Contributor
Posts: 424 Joined: Tue Aug 10, 2004 3:08 am
Post
by Mr Tech » Wed Aug 16, 2006 2:10 am
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 = "";
}
Mr Tech
Forum Contributor
Posts: 424 Joined: Tue Aug 10, 2004 3:08 am
Post
by Mr Tech » Thu Aug 17, 2006 12:19 am
Is it really that difficult? Absolutley everything works except the str_replace part... Any ideas?
CoderGoblin
DevNet Resident
Posts: 1425 Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany
Post
by CoderGoblin » Thu Aug 17, 2006 3:41 am
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.