Reputation: 1180
My understanding of Regex isn't great and I need to adapt my working JS code to PHP.
This is one of the run-throughs in JavaScript (it finds hashtags and makes HTML anchor tags out of them):
exp = /(^|\s)#(\w+)/g;
messagetext = messagetext.replace(exp, "$1<a class='myHashtag' href='http://search.twitter.com/search?q=%23$2' target='_blank'>#$2</a>");
How would this be done in PHP?
Upvotes: 0
Views: 267
Reputation: 89639
You can do it like this:
$messagetext = preg_replace('~^\h*+#\K\w++~m',
'<a class="myHashtag" '
.'href="http://search.twitter.com/search?q=%23$0" target="_blank">#$0</a>',
$messagetext);
pattern detail:
^ # line's begining
\h*+ # horizontal space (ie space or tab), zero or more times (possessive)
# # literal #
\K # forgets all the begining!
\w++ # [a-zA-Z0-9_] one or more times (possessive)
Delimiters are ~
but you can choose other characters.
I use the multiline mode (m modifier), thus ^
stands for line's begining.
(possessive) indicates to the regex engine that it don't need to backtrack by adding a +
after a quantifier. The subpattern becomes then more efficient.
Upvotes: 3