【问题标题】:Can we use Bitwise operator "|" with strpos in php?我们可以使用按位运算符“|”吗在php中使用strpos?
【发布时间】:2017-09-03 17:48:36
【问题描述】:

我们可以使用按位运算符“|”吗在php中使用strpos? 我需要检查 a0,a1,a2,a5 字符串是否存在于给定的 $status 变量中。 我的代码如下所示。只有当状态变量具有 value=a0 或 a1 或 a2 或 a5 时,我的代码才会返回值(位置)。当 $status='a1 测试字符串时,它将返回 false。

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

【问题讨论】:

  • 问题是:如何定义您实际要搜索的状态字符串的部分
  • 我需要搜索字符串($status)是否包含a1 OR a2 OR a0 OR a5
  • 如果状态字符串类似于“a2 is not the same as a5 or a3!”?
  • 状态字符串可能包含带有 a1 OR a2 OR a5 或 a0 的字符串。 .. 上面的代码只是用来检查状态字符串是否包含这些字符串(a1,a0,a2,a5)
  • 当然可以,但它会给你带来误报。

标签: php strpos


【解决方案1】:

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

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

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

【讨论】:

  • 我在一个开源项目(Open EMR)中找到了这段代码。这段代码是否正确? $status='a1 测试字符串'; echo strpos("|a0|a1|a2|a5|", $status);
  • @user1752065 让我们检查一下其他选项
【解决方案2】:

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

作为位运算符| -

作为文字符号| -

【讨论】:

  • 所以这个 '(strpos("|a0|a1|a2|a5|", $status))' 将考虑 "|a0|a1|a2|a5|"作为单个字符串 r8?
  • 我不知道在你的情况下 r8 是什么,但是,是的,确切地说,strpos"|a0|a1|a2|a5|" 视为单个字符串
【解决方案3】:

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

strpos — 查找子字符串第一次出现的位置 一个字符串

查找needle 中第一次出现的数字位置 haystack 字符串。

参数

haystack 要搜索的字符串。

needle如果 needle 不是字符串,则将其转换为整数并 用作字符的序数值。

offset 如果指定,搜索会从这个字符数开始 从字符串的开头开始计数。如果偏移量为负, 搜索将从末尾开始计数的字符数 字符串。

事实上,实现这样的功能并没有多大意义,因为你已经有了一个成熟的regular expression 引擎:

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

【讨论】:

  • 我在一个开源项目中找到了上面的代码。所以这将考虑“|a0|a1|a2|a5|”作为单个字符串 r8?
  • @user1752065 r8?我完全不知道你在说什么——记住我们无法读懂你的想法;-) 如果你对某些软件有疑问,你应该明确地问他们(当然要提供一些背景信息)。
【解决方案4】:

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

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);

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 2015-04-08
    • 1970-01-01
    • 2015-03-15
    • 2021-09-11
    • 2018-10-12
    相关资源
    最近更新 更多