views:

60

answers:

5

I have a text field in which user can enter any character he/she wants. But in server i have a string patter [a-z0-9][a-z0-9+.-]*, if any of the character in the value from the text box doesn't match the pattern, then i must remove that character from that string. How can i do that in php. is there any functions for that?

Thanks in advance. Gowri Sankar

A: 
str_replace('x','',$text);
zilverdistel
thanks for ur reply. but this will replace only the occurrence of 'x' from the string. But i need to remove any of the characters that does not match the provided pattern.
Goysar
You can also give arrays as arguments to str_replace ...
zilverdistel
Could you give examples?
zilverdistel
say i have a string like 'ThaNks, for Ur-Re/pl(y.' and my pattern is [a-z0-9][a-z0-9+.-]* and my expected result is 'thanksforur-reply.'
Goysar
In that case you need preg_replace as stated in other answers. There's a comment in the function page on php that might help you: http://de3.php.net/manual/en/function.preg-replace.php#84794
zilverdistel
+3  A: 

Just use preg_replace with the allowed pattern negated.

For example, if you allow a to Z and spaces, you simply negate it by adding a ^ to the character class:

echo preg_replace('/[^a-z ]*/i', '', 'This is a String !!!');

The above would output: This is a String (without the exclamation marks).
So it's removing any character that is not a to Z or space, e.g. your pattern negated.

Gordon
ya thanks u. I already found that function but i don't know how to neglate the allowed pattern. Because there are lots of unallowed patterns avaliable.
Goysar
@Goysar Typing a caret `^` after the opening square bracket will negate the character class.
Gordon
+1  A: 

How about:

$string = 'A quick test &*(^&for you this should work';

$searchForThis = '/[^A-Za-z \s]/';

$replaceWithBlank = '';

echo preg_replace($searchForThis, $replaceWithBlank , $string);

Martin Beeby
+3  A: 

.. in PHP we use regular Expressions with preg_replace. Here you have some help with examples... http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/

this is what you need:

$new_text = preg_replace('#[^A-Za-z+.-0-9]#s','',$text);

jatt
thank you for ur regexp it worked fantastically!
Goysar
+2  A: 

Try this:

$strs = array('+abc123','+.+abc+123','abc&+123','#(&)');
foreach($strs as $str) {
    $str = preg_replace('/(^[^a-z0-9]*)|([^a-z0-9+.-]*)/', '', $str);
    echo "'",$str,"'\n";
}

Output:

'abc123'
'abc+123'
'abc+123'
''
M42