I want to create a script that will read a string and whenever the hashtag symbol (#) appears, it replaces it with a link. How could I do this?
I've only found scripts that just replace the # and not the word it's attached to.
Thanks!
I want to create a script that will read a string and whenever the hashtag symbol (#) appears, it replaces it with a link. How could I do this?
I've only found scripts that just replace the # and not the word it's attached to.
Thanks!
well, that's exactly what you described:
So, can you explain a little further? What do you want to accomplish?
Code:1) #word => <a href="http://example.com">link</a> 2) #word => <a href="http://example.com">word</a> 3) #word => <a href="http://word">link</a> 4) #word => <a href="http://word">word</a> 5) something else?
Thanks for the reply, the second line in your code looks about what I want.
#word -> <a href='website.com/page.php?h=$word'>#word</a>
read about preg_replace().
PHP Code:
<?php #example
$text = "I want a link to the #homepage here.";
$newText = preg_replace( '/#([\w]+)/','<a href="http://website.com/page.php?h=$1">$1</a>',$text );
print $newText;
/* outputs:
I want a link to the <a href="http://website.com/page.php?h=homepage">homepage</a> here.
*/
to explain the regex:Code:/#([\w]+)/ / begin pattern # a literal "#" symbol ( begin subpattern (this allows you to backreference the match later with$1
[ begin character class (a type of character to match) \w "word character" (most characters, that don't separate words) ] end character class + one or more of the previous characters ) end subpattern (taken together, this means the "#" only qualifies if there are one or more "word characters" after it) / end pattern
Last edited by traq; 04-12-2013 at 07:36 PM.
Worked like a charm! Thanks very much for the snippet and full explanation, very helpful!
no prob, glad I could help.
If your question has been answered, please mark your thread "resolved":
- On your original post (post #1), click [edit], then click [go advanced].
- In the "thread prefix" box, select "Resolved".
- Click [save changes].
Bookmarks