[SOLVED] How to check if a string contains certain characters using an array in php


I need to check if a string contains illegal character and I was wondering if there is a way to do it through an array because I have an array character that are allowed. This is in PHP

The array just in case you want to see it:

$MsgAry1 = array("A","B","C","D","E","F","G","H","I","J",
           "9","0",".",",","'","?","!"," ","_","-");

Thanks for any help.


You can use the str_split and in_array functions to do this, as thus:

$MsgAry1 = array("A","B","C"); //Add your actual array here
$testCase = "Hello, World!";
$testCase_arr = str_split($testCase);

foreach($testCase as $test)
    if(!in_array($test, $MsgAry1))
        echo "Error! Invalid Character!";
        break(); //Or exit();, as needed

Answered By – Acharya Anurag

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *