Reputation: 299
I would like to add a link around my string which is
"My new Tweet **#new** this is cool".
And I would like to get the hashtag #new to wrap into a link.
After that, I'll get :
"My new Tweet <a href="http://twitter.com/search/%23new">new</a> this is cool.
How could I do that?
Upvotes: 1
Views: 2186
Reputation: 28891
This would probably do it:
$yourString = 'My new Tweet **#new** this is cool';
$yourString = preg_replace_callback('/\*\*(#(.+?))\*\*/', function($matches) {
$html = '<a href="http://twitter.com/search/%s">%s</a>';
return sprintf($html, urlencode($matches[1]), htmlentities($matches[2]));
}, $yourString);
Upvotes: 1
Reputation: 8169
Assuming that your hastags contain only letters and numbers, you can use the following code:
$string = preg_replace('/\*\*#([a-zA-Z0-9]+)\*\*/', '<a href="http://twitter.com/search/%23$1">$1</a>', $string);
You can easily change the content of the regex as needed.
Upvotes: 1
Reputation: 3131
Try this:
$string = "My new Tweet **#new** this is cool".
$linked_string = preg_replace('/\*\*(\#(.*?))\*\*/', '<a href="http://twitter.com/search/$1">$2</a>', $string);
Upvotes: 2