Text Size
Sunday, May 20, 2012
Get a look down
Drupal >> Displaying items by tag: preg_replace
Displaying items by tag: preg_replace

Here's a little snippet that allow's us to remove any non alphanumeric characters from strings. It would be very usefull when a developper need to format a given string from a registration form for example.

1
2
3
4
5
6
7
8
9
10
<?php
// Our string
$words = "Hello! My Name Is Nabil SADKI 007!!!";
 
// Formatted string
$formatted_words = preg_replace("[^A-Za-z0-9]", "", $words ); // This will print : HelloMyNameIsNabilSADKI007
 
// Get only alpha
$formatted_words = preg_replace("[^A-Za-z]", "", $words ); // This will print : HelloMyNameIsNabilSADKI
?>
Published in Code snippets
Usefull tricks