zahir hussain
zahir hussain

Reputation: 3739

Allow only [a-z][A-Z][0-9] and some symbols in a string

How can I get a string that only contains a to z, A to Z, 0 to 9 and some symbols?

My string is: ��S�o�n�u� �N�i�g�a�m�,� �S�a�i�n�d�h�a�v�i

I would like to eliminate the symbols.

Upvotes: 14

Views: 105535

Answers (6)

Sarfraz
Sarfraz

Reputation: 382686

You can filter it like:

$text = preg_replace("/[^a-zA-Z0-9]+/", "", $text);

Upvotes: 30

Karue Benson Karue
Karue Benson Karue

Reputation: 1026

If you need to preserve spaces in your string do this

$text = preg_replace("/[^a-zA-Z0-9 ]+/", "", $text);

Please note the way I have added space between 9 and the closing bracket. For example

$name = "!#$John Doe";
echo preg_replace("/[^a-zA-Z0-9 ]+/", "", $name);

the output will be: John Doe

Spaces in the string will be preserved.

If you fail to include the space between 9 and the closing bracket the output will be:

JohnDoe

Upvotes: 1

Aditya P Bhatt
Aditya P Bhatt

Reputation: 22071

A shortcut will be as below also:

if (preg_match('/^[\w\.]+$/', $str)) {
    echo 'Str is valid and allowed';
} else
    echo 'Str is invalid';

Here:

// string only contain the a to z , A to Z, 0 to 9 and _ (underscore)
\w - matches [a-zA-Z0-9_]+

Upvotes: 0

anon
anon

Reputation:

You can also use the Ctype functions for this, not just regular expressions:

In your case use ctype_alnum, example:

if (ctype_alnum($str)) {
    //...
}

Example:

<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
    if (ctype_alnum($testcase)) {
        echo 'The string ', $testcase, ' consists of all letters or digits.';
    } else {
        echo 'The string ', $testcase, ' don\'t consists of all letters or digits.';

    }
}

Online example: https://ideone.com/BYN2Gn

Upvotes: 13

Serge S.
Serge S.

Reputation: 4915

You can test your string (let $str) using preg_match:

if(preg_match("/^[a-zA-Z0-9]+$/", $str) == 1) {
    // string only contain the a to z , A to Z, 0 to 9
}

If you need more symbols you can add them before ]

Upvotes: 32

Alix Axel
Alix Axel

Reputation: 154533

Both these regexes should do it:

$str = preg_replace('~[^a-z0-9]+~i', '', $str);

Or:

$str = preg_replace('~[^a-zA-Z0-9]+~', '', $str);

Upvotes: 1

Related Questions