tags:

views:

328

answers:

2

Hello Peeps,

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 exampe:

echo preg_replace("/#([A-Za-z0-9_]+)(?= )/", "<a href='http://url.com/$1'&gt;$0&lt;/a&gt;", $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 dont want to include the space in the output (hence the (?= ) ) but I don't know what else I can do.

Any help would be greatly appreciated.

Thanks in advance

+2  A: 

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

ennuikiller
Wow, thank you for your speedy and very nice answer. I've made one more modification to it to not include the whitespace in the returned urls, so the final regex is:/@([A-Za-z0-9_]+)(?=\s|\Z)/Perfect, thank you very much ennuikiller. Is there anything I can do for you to as a gesture of thanks?
Jamie Bicknell
@jamie your appreciation is more than enough gesture! Maybe you'll answer one of my questions not time!
ennuikiller
i meant "next" time of course!
ennuikiller
I will keep my eyes peeled for your questions!
Jamie Bicknell
+1  A: 

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

ilya.devyatovsky
Thank you for your answer, I have also tried this and also works as well as the above regex (see comment in above answer).Thank you again for your speedy response!
Jamie Bicknell