我使用 php preg_match将变量中的第一个和最后一个单词与给定的第一个和最后一个特定单词匹配,
例子:
$first_word = 't'; // I want to force 'this'
$last_word = 'ne'; // I want to force 'done'
$str = 'this function can be done';
if(preg_match('/^' . $first_word . '(.*)' . $last_word .'$/' , $str))
{
echo 'true';
}
但问题是我想在(开始和结束)处强制匹配整个单词,而不是第一个或最后一个字符。
最佳答案
在搜索中使用 \b 作为边界 word 限制:
$first_word = 't'; // I want to force 'this'
$last_word = 'ne'; // I want to force 'done'
$str = 'this function can be done';
if(preg_match('/^' . $first_word . '\b(.*)\b' . $last_word .'$/' , $str))
{
echo 'true';
}
关于php - 匹配变量中的第一个和最后一个完整单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11490182/