Justin Erswell
Justin Erswell

Reputation: 708

Hashtag preg_replace

I have a web app which is creating and linking to #hashtags and I have noticed that if someone creates a #hashtag of #JB22 that the following code breaks.

Is there away in the regex I can allow numbers at the end of a #hashtag

$users = preg_replace("~(<var data-type=\"user\" class=\"userHighlight\" id=\"(.*?)\">)(.*?)(</var>)~", "<_link>$2|$3</_link> ", $start);
$tags = preg_replace("~(<var data-type=\"tag\" class=\"tagHighlight\" id=\"(.*?)\">)#(.*?)(</var>)~", "<_link>tag://$3|#$3</_link> ", $users);
$last = preg_replace("~(^|\\s)#(\\w*[a-zA-Z_]+\\w*)~", " <_link>tag://$2|#$2</_link> ", $tags);

Upvotes: 1

Views: 502

Answers (2)

Samuel Cook
Samuel Cook

Reputation: 16828

You should be able to add the 0-9 block to your regex to search for numbers as well:

$last = preg_replace("~(^|\\s)#(\\w*[a-zA-Z0-9_]+\\w*)~", " <_link>tag://$2|#$2</_link> ", $tags);

Note: You should be using some sort of DOM Document parser to HTML/XML mark up.

Upvotes: 3

Mihai Stancu
Mihai Stancu

Reputation: 16107

Replace this [a-zA-Z_]+ with [a-zA-Z_0-9]+ or if you want the numbers only at the end of the pattern you can use ([a-zA-Z_]+?[a-zA-Z_0-9]+?).

Upvotes: 2

Related Questions