Theodoros80
Theodoros80

Reputation: 796

preg_replace only for non-english characters

I have a function that replace all hashtag with hrefs.

function hash_me($ret) {
     $ret = preg_replace('/(\#)([^\s]+)/', ' <a href="tag/$2">#$2</a> ', $ret);
}

It works well. It will return the string(and the rest non-hashtags words)with hashtags as links.

The thing is that i want to replace with hrefs only hashtags that contain english characters.Non-english hashtags should be ignored.

How can i merge/fit :

preg_match('/#[^a-z\d]/i',$da_string)

with the above function?

Thank you!

Upvotes: 1

Views: 992

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

You can use the unicode character class Latin:

function hash_me($ret) {
     $ret = preg_replace('/#([\p{Latin}0-9]+)/', ' <a href="tag/$1">$0</a> ', $ret);
}

But keep in mind that Latin and english are two things different.

For only english characters:

function hash_me($ret) {
     $ret = preg_replace('/#([a-z0-9]+)/i', ' <a href="tag/$1">$0</a> ', $ret);
}

or shorter:

function hash_me($ret) {
     $ret = preg_replace('/#([^\W_]+)/', ' <a href="tag/$1">$0</a> ', $ret);
}

Upvotes: 3

Related Questions