I'm trying to find every instance of @username in comment text and replace it with a link. Here's my PHP so far:
我试图在注释文本中找到@username的每个实例,并用一个链接替换它。下面是我到目前为止的PHP:
$comment = preg_replace('/@(.+?)\s/', '<a href="/users/${1}/">@${1}</a> ', $comment);
The only problem is the regex is dependent upon there being whitespace after the @username reference. Can anyone help me tweak this so it will also match if it is at the end of the string?
唯一的问题是regex依赖于@username引用后的空格。谁能帮我调整一下,如果它在字符串的末尾,它也会匹配吗?
2 个解决方案
#1
9
try /@(\w+)/
instead of /@(.+?)\s/
.
试试/@(\w+)/代替/@(.+?)\s/。
#2
13
To detect whitespace or end of string, you would use: /@(.+?)(?=\s|$)/
, but unless your usernames contain non-alphanumeric characters, it's simpler to use the \w
for word character or \b
for word break, i.e.: /@(.+?)\b/
or /@(\w)+/
.
要检测空格或字符串的结尾,可以使用:/@(.+?):/ @(. + ?)\ b / / @(\ w)+ /。
#1
9
try /@(\w+)/
instead of /@(.+?)\s/
.
试试/@(\w+)/代替/@(.+?)\s/。
#2
13
To detect whitespace or end of string, you would use: /@(.+?)(?=\s|$)/
, but unless your usernames contain non-alphanumeric characters, it's simpler to use the \w
for word character or \b
for word break, i.e.: /@(.+?)\b/
or /@(\w)+/
.
要检测空格或字符串的结尾,可以使用:/@(.+?):/ @(. + ?)\ b / / @(\ w)+ /。