繁体   English   中英

匹配完整单词的字符串开头

[英]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 $-您的刺痛是“ hi”
  • ^ hi \\ s-您的字符串以hi开头:“ hi”
  • \\ shi \\ s-字符串中的某处有一个“ hi”
  • \\ shi $-您的字符串以“ hi”结尾

这些部分通过管道“ |”粘合在一起,在正则表达式中表示“或”,因此整个表达式与任何一个部分匹配

如果您针对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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM