如何检查字符串是否只包含特定字符

问题描述 投票:0回答:6

我需要检查一个字符串以确定它是否包含除

|
以外的任何字符,以便为那些除了
|
之外没有任何内容的变量分配 NULL 值(理论上可以有任意数量的
|
字符,但可能不会超过 5-6)。喜欢
||||

我可以看到循环遍历字符串的每个字符或类似的东西,但我觉得必须有一种更简单的方法。

php preg-match
6个回答
17
投票
if (preg_match('/[^|]/', $string)) {
    // string contains characters other than |
}

或:

if (strlen(str_replace('|', '', $string)) > 0) {
    // string contains characters other than |
}

3
投票

是的,您可以使用正则表达式:

if(! preg_match('/[^\|]/', $string)) {
  $string = NULL;
}

2
投票

我想检查一个字符串是否只包含某些字符。为了防止双重否定(因为我发现它们更难阅读),我决定使用以下正则表达式:

preg_match('/^[|]+$/', $string)

这会检查字符串从头到尾仅包含

|
个字符(至少一个)。


0
投票

如果字符串在从字符串前面修剪管道后具有长度,则它至少有一个非管道字符。

if (strlen(ltrim($string, '|')) {
    // has non-pipe characters
}

0
投票

count_chars
函数可能与您的用例相关:

$str = 'a|b|||e';

$chars = count_chars($str, 1); // [97 => 1, 98 => 1, 101 => 1, 124 => 4]
unset($chars[ord('|')]); // [97 => 1, 98 => 1, 101 => 1]
$chars = array_map(\chr(...), array_keys($chars)); // ['a', 'b', 'e']

-1
投票

最快、最简单的方法可能是 stripos 函数。它返回一个字符串在另一个字符串中的位置,如果找不到则返回 false:

if (false === stripos($string, '|')) {
    $string = null;
}

false ===
是严格类型比较所必需的,因为 stripos 可能返回零,表明 |位于第一个字符上。

您可以使用更复杂的验证引擎,使阅读更容易。我确实推荐尊重\验证。使用示例:

if (v::not(v::contains('|'))->validate($string)) {
    $string = null;
}
© www.soinside.com 2019 - 2024. All rights reserved.