Reputation: 6318
I have some code I that although it works, its making my content erratic. Let me explain.
I created a text chatting app for studying PHP etc and, long story short, the user types a message, the message gets logged in db and prints it back out onto the page on certain fields (below)
this is how the page gets its content (in short so I don't fill the page with code)
while($row = mysqli_fetch_array($dbqDoIt4_mssgs)){
$i++;
//====== TURN REGULAR LINKS TO CLICKY LINKS USING REGEXP.
$URL = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$text = $row['mssg'];
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "<a href='{$url[0]}'>{$url[0]}</a> ", $text);
}
//=======
echo '<div class="holdChat">
<span class="orangeBigger">' . strtoupper($row['user']). '</span>' . ' ' . '<span class="txtSaid">said:</span> ' . '<span style="color:#171717;">' . $text . '</span>' . '</div>' .
'<div class="chatTimeBox">' . $row['time'] . '</div><br/>';
if($i == 20){
break;
}
}
Essentially,this gets all the content upto 20 and breaks etc...
So with the above in ONE line, you get USER-NAME SAID: " --message here --
which
appears in a grey-ish div.
now, the problem i was having was, getting links to show as links when the echo is made to the page.
this is the code i went with (with help from others)
//====== TURN REGULAR LINKS TO CLICKY LINKS USING REGEXP.
$URL = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$text = $row['mssg'];
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "<a href='{$url[0]}'>{$url[0]}</a> ", $text);
}
//=======
The problem I'm currently having is that when a link is written in the post, it repeats the content written...or rather, it appears twice on the page. if the post doesn't have any links, it appears as it should.
so for example, without a link in the text it appears like this USER-NAME SAID: " --message here --
with any links on the text, I get a double post one on top of the other like this
USER-NAME SAID: " --message here --
USER-NAME SAID: " --message here --
which throws it all off.
I'm at my wits end...my php skill stopped there lol. Any tips / help / explanations etc ill gladly accept.
Upvotes: 0
Views: 50
Reputation: 1258
Looks like it's echo
ing right at the time it preg_replaces
, instead of saving it to be echo
ed later. Try changing:
echo preg_replace($reg_exUrl, "<a href='{$url[0]}'>{$url[0]}</a> ", $text);
To:
$text = preg_replace($reg_exUrl, "<a href='{$url[0]}'>{$url[0]}</a> ", $text);
Upvotes: 2