Jump to content

Find Links: str_replace vs. preg_replace


EternalSorrow

Recommended Posts

I'm currently working on a not-so-simple way of displaying archived news information.  Because the archive page is in a sub-folder whereas the news is normally placed in the main folder (this is for aesthetic purposes), I've run into a strange problem I'm having with the links.

 

All the links point to the correct folders when the news is in the main folder, but since the archive page is in a sub-folder, I need to place double-period-slash (../) in front of all links to point them in the right direction.  The links are strewn about the field $body, and this is where I need help.

 

I need to be able to find any instance of <a href=" and replace is with <a href="../ so all links will point to the correct folder.  I also need to find all links which have counter.php as their destination so I can make an exception to the double-period-slash rule (that page is in the same folder as the archive page, so it still points to the correction destination).

 

I can't wrap my head around whether I need to use str_replace or preg_replace in these instances, or whether both are necessary.  I also have the added difficulty of a preg_replace currently being used for the $body field to insert paragraph tags into the field.  Anyone have any ideas or tutorials on how to solve this dilemma?

 

Here's the short code for reference:

<?php

$query = "SELECT a.*, b.* FROM blog a 
            INNER JOIN blog_catjoin c ON a.entry_id = c.entry_id 
            INNER JOIN blog_category b ON b.fl_id = c.cat_id
            WHERE a.entry_id = '$entry_id2'
            GROUP BY a.entry_id
            ORDER BY a.entry_id DESC LIMIT 4";
$result = mysql_query($query) or die(mysql_error());

while ($row4 = mysql_fetch_array($result))
{
extract($row4);

$select_category = mysql_query("SELECT * FROM blog_category AS b INNER JOIN blog_catjoin AS c ON b.fl_id = c.cat_id WHERE c.entry_id = $entry_id ORDER BY b.fl_subject ASC ") or die (mysql_error());

$cat = "";
while ($row2 = mysql_fetch_array($select_category)) {
   $cat .= "<a href=\"archive_category.php?a=show&fl_subject=$row2[fl_subject]\">$row2[fl_subject]</a>, ";
}

$cat = substr($cat,0,-2);

$select_table = "SELECT *, date_format(blog.added, '%M %d, %Y') AS datetime FROM blog WHERE entry_id = $entry_id ";
$select_results = mysql_query($select_table) or die (mysql_error());
$tableArray = mysql_fetch_array($select_results) or die (mysql_error());

$body = preg_replace('#\r+#', '</p><p>', $body);

echo '<div style="overflow: hidden;">
<h3>'.$title.'</h3>
'.$body.'
<p><b>Categories:</b> '.$cat.'
<br><b>Added:</b> '.$tableArray['datetime'].'
</div>';

}
}
?>

Link to comment
Share on other sites

preg_replace would be ideal as you can make a pattern that will do the replace in 1 go, without having to go back for the exception. As far as the exact pattern goes, i'm somewhat hopeless at regex so another poster will probably have to help with that

 

Thanks for the tip!  I also am at a loss on how to handle the regex, so anyone have any ideas?  Tutorials?  Further tips?

Link to comment
Share on other sites

preg_replace_all('/(<a.*?)href\s*=\s*(['"])(\/.*?)['"](.*?>)/is','$1href=$2..$3$2$4',$body);

 

only does links without domain names :) first character in url must be /

 

 

None of my links have domain names, but neither do any of them begin with a slash.  That's what I need to implement into the URLs, along with the two periods.  I tried implementing the preg_replace_all into my code, but I now receive this error:

 

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

 

on the line holding the preg_replace_all.  Because of the complicated string, I'm not really sure what's missing or not supposed to be there.

 

Here's the new code:

<?php

$query = "SELECT a.*, b.* FROM blog a 
            INNER JOIN blog_catjoin c ON a.entry_id = c.entry_id 
            INNER JOIN blog_category b ON b.fl_id = c.cat_id
            WHERE a.entry_id = '$entry_id2'
            GROUP BY a.entry_id
            ORDER BY a.entry_id DESC LIMIT 4";
$result = mysql_query($query) or die(mysql_error());

while ($row4 = mysql_fetch_array($result))
{
extract($row4);

$select_category = mysql_query("SELECT * FROM blog_category AS b INNER JOIN blog_catjoin AS c ON b.fl_id = c.cat_id WHERE c.entry_id = $entry_id ORDER BY b.fl_subject ASC ") or die (mysql_error());

$cat = "";
while ($row2 = mysql_fetch_array($select_category)) {
   $cat .= "<a href=\"archive_category.php?a=show&fl_subject=$row2[fl_subject]\">$row2[fl_subject]</a>, ";
}

$cat = substr($cat,0,-2);

$select_table = "SELECT *, date_format(blog.added, '%M %d, %Y') AS datetime FROM blog WHERE entry_id = $entry_id ";
$select_results = mysql_query($select_table) or die (mysql_error());
$tableArray = mysql_fetch_array($select_results) or die (mysql_error());

$body = preg_replace('#\r+#', '</p><p>', $body);

$body = preg_replace_all('/(<a.*?)href\s*=\s*(['"])(\/.*?)['"](.*?>)/is', '$1href=$2..$3$2$4', $body);

echo '<div style="overflow: hidden;">
<h3>'.$title.'</h3>
'.$body.'
<p><b>Categories:</b> '.$cat.'
<br><b>Added:</b> '.$tableArray['datetime'].'
</div>';

}
}
?>

Link to comment
Share on other sites

My bad, i just wrote it without thinking bout it, or testing it

$body = preg_replace_all("/(<a.*?)href\s*=\s*(['\"])(\/.*?)['\"](.*?>)/is", '$1href=$2..$3$2$4', $body);

if all your links dont use domain names, just the filename as "index.html"
[code]$body = preg_replace_all("/(<a.*?)href\s*=\s*(['\"])(.*?)['\"](.*?>)/is", '$1href=$2../$3$2$4', $body);
shud do the trick

Link to comment
Share on other sites

The page appears, but along with this error message:

 

Fatal error: Call to undefined function preg_replace_all()

 

Through some searching I figure possibly my php isn't set up to handle the function, and doesn't recognize it as a function.  The PHP version I'm using is 5.2.8.  Anyone know what I need to change to fix the problem?

Link to comment
Share on other sites

Scratch that last post, I merely eliminated the _all and the code appears to work just fine for all links.  However, does anyone know how to exclude specific links from the new preg_replace?  Or possibly break down the current code so I can learn how to on my own?

 

A great thanks to all the wonderful help so far!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.