如何检查字符串是否包含某些字符

时间:2021-01-01 17:31:07

标签: php arrays

我正在尝试制作一个脚本来检查字符串是否包含某个字符。这是我尝试过的:

$disallowedChars = array('\', '/', ':', '*', '?', '"', '<', '>', '|');
if(in_array($string, $disallowedChars)) {
echo "String contains disallowed characters";
}

它返回此错误:

<块引用>

解析错误:语法错误,意外的':',需要')'

我认为这是因为 /:*? 都是运算符。我不明白这一点,任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

解析器错误是为此,您需要将反斜杠字符'\'转义为'\\'

less2(X, s(X)) :- numeral(X).
less2(X, s(Y)) :- less2(X,Y).

@pavel 说得对,inarray 函数不是将字符串校验为字符串,而是将值校验为数组,解决你的问题使用正则表达式更有效

in_array

PCRE Functions 用于正则表达式函数

import re
from contextlib import ExitStack

REGEX = re.compile(r"[^:\s]+:\S+")
with ExitStack() as stack:
    fr = stack.enter_context(open(input, encoding="UTF_8"))
    fw = stack.enter_context(open(output, mode="w", encoding="UTF_8"))
    for line in fr:
        match = REGEX.match(line)
        if not match:
            fw.write("\n")
            continue
        for item in REGEX.findall(line):
            fw.write(f"{item}\n")

答案 1 :(得分:0)

有错误的逻辑,您不能使用 in_array 来针对不允许的字符数组测试整个字符串。改用 foreach

<?php

$strings = [
    'Good string.',
    'Bad : string.'
];

$disallowedChars = array('\\', '/', ':', '*', '?', '"', '<', '>', '|');

// this foreach is just for looping over two strings
foreach ($strings as $str) {
    $clean = false;

    // here is the main point of your question, loop over all disallowed chars and check if char is in string (strpos)
    foreach ($disallowedChars as $dis) {
        if (strpos($str, $dis) !== FALSE) {
            $clean = true;
        }   
    }

    echo $clean ? 'String is OK' : 'String contain bad chars';
    echo '<br>';
    
    // for 'Good string.' returns 'String is OK'
    // for 'Bad : string.' returns 'String contain bad chars'
}