Php 如何检查字符串是否包含某些字符
我正在尝试制作一个脚本来检查字符串是否包含某个字符。这就是我尝试过的:Php 如何检查字符串是否包含某些字符,php,arrays,Php,Arrays,我正在尝试制作一个脚本来检查字符串是否包含某个字符。这就是我尝试过的: $disallowedChars = array('\', '/', ':', '*', '?', '"', '<', '>', '|'); if(in_array($string, $disallowedChars)) { echo "String contains disallowed characters"; } $disallowedChars=array(“\”、“/”、
$disallowedChars = array('\', '/', ':', '*', '?', '"', '<', '>', '|');
if(in_array($string, $disallowedChars)) {
echo "String contains disallowed characters";
}
$disallowedChars=array(“\”、“/”、“:”、“*”、“?”、“”、“|”);
if(在数组中($string,$disallowedChars)){
echo“字符串包含不允许的字符”;
}
它返回以下错误:
分析错误:语法错误,意外的“:”,应为“)”
我想这是因为
/
,:
,*
和?
都是运算符。我不理解这一点,非常感谢您提供任何帮助。解析器错误就是因为这样,您需要将反斜杠字符“\”转义为“\”
$disallowedChars = array('\\', '/', ':', '*', '?', '"', '<', '>', '|');
$disallowedChars=array(“\\\”、“/”、“:”、“*”、“?”、““”、“|”);
@pavel有权,inarray函数不将字符串检入字符串,是为了将值检入数组,为了解决您的问题,使用正则表达式更有效
对于正则表达式函数
$test = [
'good string....'.
'another string,,,',
'bad maur\\fsdf',
'bad dsfdsf:fgdf',
'bad fdsd<fdsff',
'bad dfdsfsdf>dfsf',
'bad dfsdf|dfsdf',
];
$regex = '~[\\\\/\:\*\?"<>\|]~m';
foreach($test as $text) {
if(preg_match($regex, $text)) {
echo "{$text} contains disallowed characters\n";
}
}
$test=[
“好的字符串…”。
'另一个字符串,,',
“bad maur\\fsdf”,
“错误的dsfdsf:fgdf”,
“错误的fdsddfsf”,
“错误的dfsdf | dfsdf”,
];
$regex='~[\\\\/\:\*\?“\\\;]~m';
foreach($testas$text){
if(preg_match($regex,$text)){
回显“{$text}包含不允许的字符\n”;
}
}
存在错误的逻辑,您不能在数组中使用来针对不允许的字符数组测试整个字符串。请改用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'
}
你是对的,但它并没有解决主要问题-它是在脚本逻辑中,而且在数组中的使用不好。哇,我很不好意思我没有想到这一点。谢谢!