[英]Match beginning of string in full words
我在这里使用startsWith()函数,在PHP中是startsWith()和endsWith()函数
但是我希望它只匹配完整的单词。
目前,它将匹配以下内容:
hi
high
hiho
但是我希望它只匹配“ hi”,如果输入是,则不匹配其他两个单词:
hi there
您可以使用以下正则表达式对其进行匹配:/ ^ hi $ | ^ hi \\ s | \\ shi \\ s | \\ shi $ /
$test = ['hi', 'hi there', 'high', 'hiho'];
$pattern = '/^hi$|^hi\s|\shi\s|\shi$/';
$matches = [];
foreach ($test as $t) {
var_dump($t);
preg_match($pattern, $t, $matches);
var_dump($matches);
}
零件说明:
这些部分通过管道“ |”粘合在一起,在正则表达式中表示“或”,因此整个表达式与任何一个部分匹配
如果您针对hi
字词测试全文,请尝试以下操作:
<?php
preg_match_all('@hi\s@i',
"hi me
hi there
high
highlander
historic
hire",
$matches);
var_dump($matches);
测试-在此处修改: https : //regex101.com/r/tV3jR6/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.