View Full Version : trying to search a string for certain strings and replace them with a new string

08-20-2012, 12:17 AM
Hi All,

Ok i am doing some work for my local football team, and i have a db table with players names and another with fixture details.

Now in the fixture details i have a field for match report which is a long text field type.

What i am trying to do is create a function which replaces all the instances of each player name found in the report with the players name but hyper linked to his profile page.

so for example if my name was in the report the function would produce the following
Luke Jackson => <a href='staff_profile.php?id=10929'>Luke Jackson</a>

So i tried this

function FindNames($report)
$sql = mysql_query("SELECT staffID, staffName FROM tbl_staff");
$id = $row['staffID'];
$name = $row['staffName'];
$addLink = str_replace($name, "<a href='staff_profile.php?id=$id'>$name</a>", $report);
return $report;

and tried echoing the match report out like so

<?php echo FindNames($report)?>

but it doesnt replace any of the names found in the report, nothing changes :( any ideas what i doing wrong?

many thanks

08-20-2012, 12:51 AM
As you are specifically treating the returned data as an associative array then you should use mysql_fetch_assoc. Or, if you insist,

while ($row=mysql_fetch_array($sql, MYSQL_ASSOC))

The replacements are performed left-to-right. So replacing $name with more text that also includes $name may be causing an issue as well.

[If this is an issue then one way around this that occurs to me is to replace $name with XXXXXX, then, immediately after, to replace XXXXXX with $name.]

BTW mysqli is recommended and use of mysql is discouraged. But you are by no means alone in side-stepping this advice?!

08-20-2012, 12:55 AM
Also, if

<?php echo FindNames($report)?>

echo's $report in full, but completely unaltered, then this suggests to me that the space between the first and last-name is an issue (as it doesn't find the name(s) at all).

08-20-2012, 01:00 AM
thanks mate, i also just noticed that im returning

return $report;

but the new text with all the replacements is called

$addLink = str_replace($name, "<a href='staff_profile.php?id=$id'>$name</a>", $report);

so i renamed $addLink to $report and it works a treat :) thanks for your help

08-20-2012, 01:15 AM
That was the first thing I noticed (he, he) but I made the incorrect assumption that it was making the replacements to $replace, so assumed that this wasn't the issue. Anyway.. :thumbsup:

BTW I still think using mysql_fetch_assoc is more sensible :)