Jump to content

Need help making script better


chrissie

Recommended Posts

Hi, I am fairly newish to php and I hacked together the following from various bits and pieces on the web. I think it is a really bad way of doing it and would like to know a better way. Basically the words in bold tags are the names for articles/future articles and if there is a article it turns it into a link.

[code]$result_nearby = mysql_query("SELECT text FROM content  WHERE id = '$id' ") or die(mysql_error());
while($row_nearby= mysql_fetch_array( $result_nearby)) {
$text= $row_nearby['text'];

preg_match_all ("/<b>([^`]*?)<\/b>/", $text, $matches);
foreach ($matches[0] as $match) {
$matchq = strip_tags($match);

$result_nearby_get = mysql_query("SELECT  ID FROM text  WHERE title = '$matchq' ") or die(mysql_error());
while($row_nearby_get= mysql_fetch_array( $result_nearby_get)) {
$replaced = str_replace($match, '<a href="/mission/'. $row_nearby_get['ID'].'.php">'.$match.'</a>', $text);
$string = $replaced;
}
}
}
print $text;[/code]

It works but if I have lots of replaces it is going to be a hog. How could it be done more streamlined? Thanks for any help.
Link to comment
https://forums.phpfreaks.com/topic/35980-need-help-making-script-better/
Share on other sites

Try this. It works in my head, at least..

[code]
<?php
function replaceboldwithlink($text) {
//Fill the matches array with...matches
preg_match_all ("/<b>([^`]*?)<\/b>/", $text, $matches);

//Get all articles and toss them in an array
mysql_query("SELECT title, ID FROM text") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$articles[$row['ID']] = $row['title'];
}

//Throw them together and see what matches
foreach($matches[0] as $match) {
unset($key);
$key = array_search($match, $articles);
if($key) {
//If there is a match, replace it!
$text = str_replace($match, '<a href="/mission/'. $key .'.php">'.$match.'</a>', $text);
}
}
return $text;
}

$result_nearby = mysql_query("SELECT text FROM content  WHERE id = '$id' ") or die(mysql_error());
$row_nearby = mysql_fetch_assoc($result_nearby);
$text= replaceboldwithlink($row_nearby['text']);

print $text;[/code]

The problem with your code is the amount of MySQL queries you're doing. You're doing one every single time there is a bold tag. As long as you don't have a huge amount of articles, it should be better to just get all of the possible articles in to an array first.

If you want something faster than this, or if you have a lot more articles than I'm assuming you have, then do something like this:
"SELECT  ID FROM text  WHERE title IN ($match[0], $match[1], $match[2]..."

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.