0

I have this PHP code:

$y = $_POST['message'];

$pre = htmlspecialchars($y, ENT_QUOTES);

$msg = str_replace("&lt;br&gt;", "<br>", $pre);

That replaces all the converted <br>'s (&lt;b&gt;) back to <br>. And I am trying to do the same (well, almost) with all the links, somewhat like in the forums. Example...

http://www.example.com

Should be wrapped around like this:

<a href="http://www.example.com">http://www.example.com</a>

IF it's easier, I would obviously prefer the [URL] [/URL] method, likewise, [IMG] [/IMG].

Could someone point me in the right direction? I have been looking for hours here, and nothing adjusts to my need :/

1

2 Answers 2

1

A VERY simple way of doing it:

$input = '[URL]xxx[/URL]';

$url = explode('[URL]', $input);
$url = explode('[/URL]', $url[1]);
$url = '<a href="' . $url[0] . '"/>Link</a>';

echo $url;

There are most certainly better ways of doing this. Maybe with regex or preg_replace.

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! Thank you! Works perfectly! And I can use it with images!! Much obliged!
:) But never forget about safety! You never know what users will input ;)
0

This is usually done with regular expressions, where you can google link regex and you'll be given a bunch of examples and tutorials. However if $_POST['message'] isn't a huge string and doesn't contain a LOT of links you can actually explode on [URL] and then find [/URL] in the array result of explode() and calculate the link length. From there you just need to append the anchor tag and substr the link as you already know the length from the original array element.

2 Comments

It's not a huge string, but either way, I don't know how to limit it to a small number of characters (500, ex) :S (In the PHP side, because I can validate it with JavaScript easily). And I'm not a great coder myself, in the PHP turf, so I'll take the sweat little deary example Patrick Browers did :)
It is basically what I suggested but written in code instead :D It's okay if you chose to do it this way but you should be aware of the fact that it is extremely inefficient and should not be used with huge texts or a lot of requests. Good luck! :P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.