user128161
user128161

Reputation:

Convert all hashtags in text to hyperlinks

I have the following string:

$str = '#hello how are #you and #you and #you';

I would like to wrap some html around those which have the hash tag in front of them, for example:

echo preg_replace("/#([A-Za-z0-9_]+)(?= )/", "<a href='http://example.com/$1'>$0</a>", $str);

Which will output:

#hello how are #you and #you and #you

Notice that each URL link has not got the hash tag in the link.

However, this is my problem, because of there is no space at the end of the last #you it doesn't match the regex and obviously doesn't get included. I'm not sure what to do really, as some may have spaces after, and some might not, but I don't want to include the space in the output (hence the (?= ) ) but I don't know what else I can do.

Upvotes: 1

Views: 1867

Answers (2)

ilya.devyatovsky
ilya.devyatovsky

Reputation: 134

You can switch the selector to the exclude mode such as ([^ ,.]+). Thus should work for all of the instances.

Upvotes: 0

ennuikiller
ennuikiller

Reputation: 46985

use (\s|\Z) this will match either whitespace or the end-of-line

Upvotes: 2

Related Questions