在完全匹配正则表达式中使用变量


Using variable in exact match regex

我有一个字符串,我想完全匹配。

到目前为止,我拥有的代码:

<?php
$string = "Such asinine comments such as";
$findStr = "such as";
$result = preg_match("/['b$findStr'b]/i", $string, $matches, PREG_OFFSET_CAPTURE, $offset);
//$result = preg_replace("/^$findStr$/i", "such&#160;as", $string);
echo $result;
echo "Offset = ".$offset."'n";
var_dump($result);
var_dump($matches);
?>  

我得到的输出:

1Offset = 
int(1)
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(1) " "
    [1]=>
    int(4)
  }
}  

我该怎么做才能获得完全匹配?到目前为止,我已经尝试了以下正则表达式:

/'b[$findStr]'b/i
/^$findStr$/i #$findStr#i

我哪里出错了?

对于完全匹配,您不需要正则表达式。你可以使用 strpos()

$pos = strpos($string, $findStr);
// Note our use of ===.  Simply == would not work as expected
// because the position might be the 0th (first) character.
if ($pos === false) {
    //string not found
} else {
    //string found at position $pos
}

不需要将模式放在字符类中。

preg_match("~'b".$findStr."'b~i", $string, $matches, PREG_OFFSET_CAPTURE, $offset);

我认为问题只出在[]字符类上。下面对我来说很好用。请注意,每当在正则表达式中使用变量时,都必须将模式或正则表达式括在双引号中,而不是用单引号引起来。因为单引号不会扩展变量。

preg_match("~'b$findStr'b~i", $string, $matches, PREG_OFFSET_CAPTURE, $offset);

这是代码:

<?php
$string = 'Test Case';
$search_term = 'Test';
if(preg_match("~'b" . $search_term . "'b~", $string)){
  echo "Matched";
} else {
  echo "No match";
}
?>