2

I have a strange question maybe you could help me with. I am trying to check whether the given string contains special characters. The code below is working however one character seems to get exempted on the condition which is the square brackets [ ]. Can you help me with this? thank you.

    $string = 'starw]ars';

    if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string)) {
        echo 'Output: Contains Special Characters';
    }else{
        echo 'Output: valid characters';
    }

Please note: I can't use below condition since I need to accept others characters from other languages like in arabic, chinese, etc. so it means I need to specify all characters that is not allowed.

    if (!preg_match('/[^A-Za-z0-9]/', $string))

Appreciate your help. Thanks.

shifu
  • 672
  • 8
  • 37

4 Answers4

2

You should add escaped square brackets to your expression.

preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-\[\]]/', $string)

EDIT: Apologies to @Thamilan, I didn't see your comment.

EDIT 2: You could also use the preg_quote function.

preg_match(preg_quote('\'^£$%&*()}{@#~?><>,|=_+¬-[]', '/'), $string);

The preg_quote function will escape your special characters for you.

Jim Wright
  • 5,905
  • 1
  • 15
  • 34
2

Use strpos:

$string = 'starw]ars';

if (strpos($string, ']') !== false) {
    echo 'true';
}

Please see the following answer for additional information: How do I check if a string contains a specific word in PHP?

Julien Ambos
  • 2,010
  • 16
  • 29
  • 1
    Nice answer for only searching `]` but OP asks "I am trying to check whether the given string contains special characters. The code below is working however one character seems to get exempted on the condition which is the square brackets [ ]." – Shaunak Shukla May 24 '17 at 09:53
2

You forgot to add square brackets [] in your expression. I have added this \[\] in your current expression.

Try this code snippet here

<?php

ini_set('display_errors', 1);

$string = 'starw]ars';

if (preg_match('/[\[\]\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string))
{
    echo 'Output: Contains Special Characters';
} else
{
    echo 'Output: valid characters';
}
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
0

Try this example:

<?php
$string = 'starw]]$%ars';
if (preg_match('/[\'\/~`\!@#\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/', $string))
{
    echo 'Output: Contains Special Characters';
} else
{
    echo 'Output: valid characters';
}
?>

Output:

Output: Contains Special Characters

RaMeSh
  • 3,330
  • 2
  • 19
  • 31