正则表达式 - 单词匹配和特殊字符
regex - word matching and special characters
我想匹配一个没有被 letter
、number
、special character
等包围的词。我想要的示例:
单词是:Hello
我使用的正则表达式示例:/\bHello\b/i
PHP 我想使用正则表达式的代码:
$text = preg_replace('/\bHello\b/i',"some img url",$text);
结果:
hello # match *(that's ok)*
hellos # no match *(that's ok)*
hello3 # no match *(that's ok)*
1hello # no match *(that's ok)*
shello # no match *(that's ok)*
$hello# # match *(that's not ok. I don't want matching!)*
hello# # match *(that's not ok. I don't want matching!)*
我只想在单词未被任何其他 letter
、number
或 SPECIAL CHARACTER
.
包围时进行匹配
单词边界适用于字母和数字,但 WordB 不适用于特殊字符,我想要类似 WordB 的东西。也适用于特殊字符...
我试过这个 "/(^|\s)Hello($|\s)/i"
但不是这样..
no letter, number, special character
如果那只意味着 "hello" 那么使用:
/^hello$/gi
正则表达式:
/(?<!\S)hello(?!\S)/i
PHP:
$text = preg_replace('/(?<!\S)hello(?!\S)/i', "some img url", $text);
您应该检查下一个或上一个字符是否不是非 space 字符。单词边界仅适用于 [0-9a-zA-Z_]
个字符(或任何语言中的任何单词字符)
以外的边界
我想匹配一个没有被 letter
、number
、special character
等包围的词。我想要的示例:
单词是:Hello
我使用的正则表达式示例:/\bHello\b/i
PHP 我想使用正则表达式的代码:
$text = preg_replace('/\bHello\b/i',"some img url",$text);
结果:
hello # match *(that's ok)*
hellos # no match *(that's ok)*
hello3 # no match *(that's ok)*
1hello # no match *(that's ok)*
shello # no match *(that's ok)*
$hello# # match *(that's not ok. I don't want matching!)*
hello# # match *(that's not ok. I don't want matching!)*
我只想在单词未被任何其他 letter
、number
或 SPECIAL CHARACTER
.
单词边界适用于字母和数字,但 WordB 不适用于特殊字符,我想要类似 WordB 的东西。也适用于特殊字符...
我试过这个 "/(^|\s)Hello($|\s)/i"
但不是这样..
no letter, number, special character
如果那只意味着 "hello" 那么使用:
/^hello$/gi
正则表达式:
/(?<!\S)hello(?!\S)/i
PHP:
$text = preg_replace('/(?<!\S)hello(?!\S)/i', "some img url", $text);
您应该检查下一个或上一个字符是否不是非 space 字符。单词边界仅适用于 [0-9a-zA-Z_]
个字符(或任何语言中的任何单词字符)