我使用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作为单词的边界限制:
$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';
}
我会用一种稍微不同的方式来处理这个问题:
$firstword = 't';
$lastword = 'ne';
$string = 'this function can be done';
$words = explode(' ', $string);
if (preg_match("/^{$firstword}/i", reset($words)) && preg_match("/{$lastword}$/i", end($words)))
{
echo 'true';
}
==============================================
以下是实现相同的另一种方法
$firstword = 'this';
$lastword = 'done';
$string = 'this can be done';
$words = explode(' ', $string);
if (reset($words) === $firstword && end($words) === $lastword)
{
echo 'true';
}
这总是会回应true,因为我们知道第一个词和最后一个词是正确的,试着把它们改成其他的,它不会回应true。
我写了一个函数来获取句子的开头,但其中没有任何正则表达式。
你可以这样写到最后。我不为结尾添加函数,因为它很长。。。
<?php
function StartSearch($start, $sentence)
{
$data = explode(" ", $sentence);
$flag = false;
$ret = array();
foreach ($data as $val)
{
for($i = 0, $j = 0;$i < strlen($val), $j < strlen($start);$i++)
{
if ($i == 0 && $val{$i} != $start{$j})
break;
if ($flag && $val{$i} != $start{$j})
break;
if ($val{$i} == $start{$j})
{
$flag = true;
$j++;
}
}
if ($j == strlen($start))
{
$ret[] = $val;
}
}
return $ret;
}
print_r(StartSearch("th", $str));
?>