Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-检查字符串中是否包含非法字符_Php_String - Fatal编程技术网

PHP-检查字符串中是否包含非法字符

PHP-检查字符串中是否包含非法字符,php,string,Php,String,在JS中,您可以执行以下操作: var chs = "[](){}"; var str = "hello[asd]}"; if (str.indexOf(chs) != -1) { alert("The string can't contain the following characters: " + chs.split("").join(", ")); } 如何在PHP中实现这一点(用echo替换警报) 我不想使用正则表达式来简化我的想法 编辑: 我所尝试的: <?

在JS中,您可以执行以下操作:

 var chs = "[](){}";
 var str = "hello[asd]}";
 if (str.indexOf(chs) != -1) {
    alert("The string can't contain the following characters: " + chs.split("").join(", "));
 }
如何在PHP中实现这一点(用echo替换警报)

我不想使用正则表达式来简化我的想法

编辑:

我所尝试的:

 <?php
    $chs = /[\[\]\(\)\{\}]/;
    $str = "hella[asd]}";
    if (preg_match(chs, str)) {
       echo ("The string can't contain the following characters: " . $chs);
    }
 ?>

在php中,您应该执行以下操作:

$string = "Sometring[inside]";

if(preg_match("/(?:\[|\]|\(|\)|\{|\})+/", $string) === FALSE)
{
     echo "it does not contain.";
}
else
{
     echo "it contains";
]
正则表达式表示检查字符串中是否有任何字符。您可以在此处阅读更多信息:

关于PHP preg_match():

更新:

我已经为此编写了一个更新的正则表达式,它捕获了其中的字母:

$rule = "/(?:(?:\[([\s\da-zA-Z]+)\])|\{([\d\sa-zA-Z]+)\})|\(([\d\sa-zA-Z]+)\)+/"
$matches = array();
if(preg_match($rule, $string, $matches) === true)
{
   echo "It contains: " . $matches[0];
}
它返回如下内容:

It contains: [inside]
我只更改了regex,它变成:

$rule = "/(?:(?:(\[)(?:[\s\da-zA-Z]+)(\]))|(\{)(?:[\d\sa-zA-Z]+)(\}))|(\()(?:[\d\sa-zA-Z]+)(\))+/";
//它返回出现的非法字符数组


现在,它返回
[]
,对于此
“我[很好]”

为什么不尝试str\u replace

<?php    

$search  = array('[',']','{','}','(',')');
    $replace = array('');
    $content = 'hella[asd]}';
    echo str_replace($search, $replace, $content);
 //Output => hellaasd

?>


对于这种情况,我们可以使用字符串替换来代替正则表达式。

这里有一个不使用正则表达式的简单解决方案:

$chs = array("[", "]", "(", ")", "{", "}");
$string = "hello[asd]}";
$err = array();

foreach($chs AS $key => $val)
{
    if(strpos($string, $val) !== false) $err[]= $val; 
}

if(count($err) > 0)
{
    echo "The string can't contain the following characters: " . implode(", ", $err);
}

请解释下一票。我没有下一票,但原因可能是你没有展示出你自己试图解决的问题。是的,看起来好多了。记住在一个问题中展示你自己的尝试。它显示了您的努力,也为我们提供了一个基本的起点。@artm认为代码太少会很明显,而我从错误的起点开始,使用正则表达式。这可能对您来说很明显,但对我们来说却不明显。当你没有发布你已经尝试过的东西时,会让人觉得你是带着你遇到的第一个问题来到这里的,而自己却没有尝试过任何东西。这里的人不太热衷于为他人解决问题,但需要看到一个尝试。但我想做的是:回显“它包含”。chars,它不适用于正则表达式,我清楚地说我不想使用正则表达式。我想要一个精确的翻译。我已经更新了这个问题,它可以满足您的需求@Murplyx