I want to be able to click on each @.... and go to their specific page so I'm getting the id's from the database for each match in the text in order to link to the match's page. I do get an array of id's from the foreach loop but when I am using preg_replace in the foreach loop, I am getting the same id inserted for multiple values. I'm stuck and have tried many different variations but no luck yet.
$text = "I went to the dog park yesterday and saw @dog4 playing with @dog8 and @dog3 drinking water.";
public function getLinks($text) {
preg_match_all("/@([\w]+)/", $text, $matches);
if ($matches) {
$result = array_values($matches[1]);
}
$sql = "SELECT dogId FROM dogs WHERE dogName = :dogName";
foreach ($result as $dogName) {
$stmt = $this->con->prepare($sql);
$stmt->execute(array(":dogName" => $dogName));
$data = $stmt->fetch(PDO::FETCH_ASSOC);
$i = 0;
if (!empty($data)) {
foreach ($data as $dogId) {
$i++;
// It's working here. I'm getting an array of dogIds
echo '<pre>'; print_r($data); echo '</pre>';
Array
(
[dogId] => 4
)
Array
(
[dogId] => 8
)
Array
(
[dogId] => 3
)
if ($i == count($data)) {
$pattern = "/@([\w]+)/";
$dogPage = "<span onclick='openPage(\"dogs.php?id=$dogId\")' role='link' tabindex='0'>$0</span>";
$dogLink = preg_replace($pattern, $dogPage, $text);
// It's not working here. I only get the last array value(3) inserted in $dogId for every match.
echo '<pre>'; print_r($dogPage); echo '</pre>';
"<span onclick='openPage(\"dogs.php?id=3\")' role='link' tabindex='0'>@dog4</span>"
"<span onclick='openPage(\"dogs.php?id=3\")' role='link' tabindex='0'>@dog8</span>"
"<span onclick='openPage(\"dogs.php?id=3\")' role='link' tabindex='0'>@dog3</span>"
}
}
}
} return $dogLink
}
The resulting text that I'm getting is
I went to the dog park yesterday and saw @dog4(id=3) playing with @dog8(id=3) and @dog3(id=3) drinking water.
But what I'm looking to achieve is
I went to the dog park yesterday and saw @dog4(id=4) playing with @dog8(id=8) and @dog3(id=3) drinking water.
Thank you in advance!