PHP的strpos函数中的通配符

4

我正在寻找一些类似于preg_replacepreg_match中使用的通配符,用于strpos函数中,但是我找不到任何相关信息,这里有一个想法:

<?php
if (strpos("The black\t\t\thorse", "black horse") === false)
  echo "Text NOT found.";
else
  echo "Text found.";
?>

这里的结果将会是:未找到文本。

现在我想使用一个通配符来忽略空格或制表符,如下所示:

<?php
if (strpos("The black\t\t\thorse", "black/*HERE THE WILDCARD*/horse") === false)
  echo "Text NOT found.";
else
  echo "Text found.";
?>

这里的意思是结果为:找到文本。

有人了解吗?


你找不到它是因为它不存在,strpos 只能进行精确匹配。如果你想使用通配符,你必须使用正则表达式。 - Barmar
如果你需要通配符,为什么不使用preg_match呢? - Amal Murali
我正在使用strpos函数,因为我试图在一个文件中找到一个由3行代码组成的代码块,并用另一个文本块替换它,你知道有什么函数可以使这个过程更容易吗? - Rolige
2个回答

2

strpos()无法匹配模式,如果您想匹配模式,则必须使用preg_match(),这对您的情况应该有效。

<?php
    if (preg_match('/black[\s]+horse/', "The black\t\t\thorse"))
      echo "Text found.";
    else
      echo "Text not found.";
?>

1
我正在使用 strpos 函数,因为我想在一个文件中查找一个由3行代码组成的代码块,并将其替换为另一个文本块,你知道有什么函数可以使这个过程更容易吗? - Rolige

0
如果您需要匹配的第一个出现,则可以使用PREG_OFFSET_CAPTURE标志:
preg_match('/black\shorse/i', "The black\t\t\thorse", $matches, PREG_OFFSET_CAPTURE);
var_dump($matches);

会导致

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

其中 $matches[0][1] 是您的位置


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接