View Full Version : PHP Find Symbol and Replace It With The Word It Goes With
M2com
04-08-2013, 03:34 PM
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've only found scripts that just replace the # and not the word it's attached to.
well, that's exactly what you described:
I want to create a script that will read a string and whenever the hashtag symbol (#) appears, it replaces it with a link
So, can you explain a little further? What do you want to accomplish?
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?
M2com
04-12-2013, 07:03 PM
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() (http://php.net/preg_replace).
<?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:
/#([\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
M2com
04-14-2013, 11:46 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].
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.