Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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?

share|improve this question
5  
using preg_replace(), for starters – Wiseguy Jun 8 '13 at 2:55
    
The documentation is quite a helpful resource, a Google search is all it takes: php.net/manual/en/function.preg-replace.php – Qantas 94 Heavy Jun 8 '13 at 2:56

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.

share|improve this answer
    
Awesome, thank you! – tylerl Jun 8 '13 at 3:13
    
Actually, is it possible to do this using my original regexp? My expression didn't include the #, which was important. I could run another function to remove the # afterwards, but I'd like to avoid that... – tylerl Jun 8 '13 at 6:55
    
@tylerl, you can use exactly the same regex in PHP as your JS regex without modifications. That you even ask this without trying... See comments on your question. – Qtax Jun 8 '13 at 7:43
    
@tyler: as Qtax say, you can use your regex and replacement, but note that my expression don't include the # too cause i use the \K trick. – Casimir et Hippolyte Jun 8 '13 at 12:28
    
Ahhh! I see now, I guess (late!) last night when I tried it I gave up with my regexp when it was producing completely blank text - I tried it again and removed the g at the end... Thanks for the help! – tylerl Jun 8 '13 at 16:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.