我们可以使用位运算符“|”吗?在 php 中使用 strpos?

Can we use Bitwise operator "|" with strpos in php?

我们可以使用位运算符“|”吗?在 php 中使用 strpos? 我需要检查给定的 $status 变量中是否存在 a0,a1,a2,a5 字符串。 仅当状态变量具有 value=a0 或 a1 或 a2 或 a5 时,我的代码才会 return 值(位置)。它将 return false when $status='a1 test string.

 $status='a1 test string';
 echo strpos("|a0|a1|a2|a5|", $status);

你可以这样使用它。这里|表示or

<?php 
$status='a1 test string';

if(preg_match("/\b(a0|a1|a2|a5)\b/", $status))
{
    echo "Matched";
}

Can we use Bitwise operator "|" with strpos in php?

作为按位运算符 | -

作为文字符号 | -

不,你不能。 Documentation 没有提到任何类似的东西:

strpos — Find the position of the first occurrence of a substring in a string

Find the numeric position of the first occurrence of needle in the haystack string.

Parameters

haystack The string to search in.

needle If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

offset If specified, search will start this number of characters counted from the beginning of the string. If the offset is negative, the search will start this number of characters counted from the end of the string.

事实上,实现这样的功能没有多大意义,因为您已经拥有成熟的 regular expression 引擎:

$has_substrings = (bool)preg_match('/a0|a1|a2|a5/u', $status);

您不能通过单个字符串搜索来做到这一点。您需要使用可以一次测试多个选项的正则表达式,或者您需要迭代搜索词。

Sahil Gulati 给出了一个基于正则表达式的方法的简单示例。

这是一个简单的基于迭代的方法:

<?php
$status = 'a1 test string';
$search = explode('|', substr("|a0|a1|a2|a5|", 1, -1));
// would be much easier to start with an array of search tokens right away: 
// $search = ['a0', 'a1', 'a2', 'a5'];

$result = false;
array_walk($search, function($token) use ($status, &$result) {
    $result = (FALSE!==strpos($status, $token)) ? true : $result;
});
var_dump($result);