문제

I'm writing a small PHP script to grab the latest half dozen Twitter status updates from a user feed and format them for display on a webpage. As part of this I need a regex replace to rewrite hashtags as hyperlinks to search.twitter.com. Initially I tried to use:

<?php
$strTweet = preg_replace('/(^|\s)#(\w+)/', '\1#<a href="http://search.twitter.com/search?q=%23\2">\2</a>', $strTweet);
?>

(taken from https://gist.github.com/445729)

In the course of testing I discovered that #test is converted into a link on the Twitter website, however #123 is not. After a bit of checking on the internet and playing around with various tags I came to the conclusion that a hashtag must contain alphabetic characters or an underscore in it somewhere to constitute a link; tags with only numeric characters are ignored (presumably to stop things like "Good presentation Bob, slide #3 was my favourite!" from being linked). This makes the above code incorrect, as it will happily convert #123 into a link.

I've not done much regex in a while, so in my rustyness I came up with the following PHP solution:

<?php
$test = 'This is a test tweet to see if #123 and #4 are not encoded but #test, #l33t and #8oo8s are.';

// Get all hashtags out into an array
if (preg_match_all('/(^|\s)(#\w+)/', $test, $arrHashtags) > 0) {
  foreach ($arrHashtags[2] as $strHashtag) {
    // Check each tag to see if there are letters or an underscore in there somewhere
    if (preg_match('/#\d*[a-z_]+/i', $strHashtag)) {
      $test = str_replace($strHashtag, '<a href="http://search.twitter.com/search?q=%23'.substr($strHashtag, 1).'">'.$strHashtag.'</a>', $test);
    }
  }
}

echo $test;
?>

It works; but it seems fairly long-winded for what it does. My question is, is there a single preg_replace similar to the one I got from gist.github that will conditionally rewrite hashtags into hyperlinks ONLY if they DO NOT contain just numbers?

도움이 되었습니까?

해결책

(^|\s)#(\w*[a-zA-Z_]+\w*)

PHP

$strTweet = preg_replace('/(^|\s)#(\w*[a-zA-Z_]+\w*)/', '\1#<a href="http://twitter.com/search?q=%23\2">\2</a>', $strTweet);

This regular expression says a # followed by 0 or more characters [a-zA-Z0-9_], followed by an alphabetic character or an underscore (1 or more), followed by 0 or more word characters.

http://rubular.com/r/opNX6qC4sG <- test it here.

다른 팁

It's actually better to search for characters that aren't allowed in a hashtag otherwise tags like "#Trentemøller" wont work.

The following works well for me...

preg_match('/([ ,.]+)/', $string, $matches);

I have devised this: /(^|\s)#([[:alnum:]])+/gi

I found Gazlers answer to work, although the regex added a blank space at the beginning of the hashtag, so I removed the first part:

(^|\s)

This works perfectly for me now:

#(\w*[a-zA-Z_0-9]+\w*)

Example here: http://rubular.com/r/dS2QYZP45n

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top