Vishesh Joshi
Vishesh Joshi

Reputation: 1611

Detecting a subset of special characters php

I have a string and the validity of the string is defined as:

  1. The string can have alphanumeric characters or (_) or (.) or (-).
  2. No other special characters are allowed.

Is there a way to allow only certain special characters in php??

Upvotes: 1

Views: 277

Answers (2)

Andrew De Forest
Andrew De Forest

Reputation: 7408

You could try looping through each character in the string and checking it individually

for($i = strlen($string); $i >= 0; $i--)
{
    $check = $string[$i];
    if(ctype_alnum($check) || $check == "_" || $check == "." || $check == "-")
    {
        //Code if good

    }
    else
    {
        //Code if bad
    }
}

Upvotes: 0

anubhava
anubhava

Reputation: 786289

You can use code like this to only allow a text with your allowed character set:

if (preg_match('/^[\w.-]+$/', $str))
    echo "valid $str\n";
else
    echo "invalid $str\n";

Upvotes: 2

Related Questions