PHP: Match Non-Alphanumeric Characters from a String

Posted on October 5, 2008, under PHP,  Bookmark it

This is a snippet that matches non-alphanumeric characters from a string (text).

<?php
function match_non_alphanumeric_characters($string, $strip_space = true) // Match spaces?
{
$str = ($strip_space) ? ' ' : '';
preg_match_all('/([^a-zA-Z0-9'.$str.']+)/', $string, $match);

return $match[0];
}

$string = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent porttitor euismod enim # Sed posuere & Duis non elit * Sed tempus dolor$';

$non_alphanumeric_array = match_non_alphanumeric_characters($string);

echo '<pre>'; print_r($non_alphanumeric_array); echo "</pre>";
?>

Output:

Array
(
    [0] => ,
    [1] => .
    [2] => #
    [3] => &
    [4] => *
    [5] => $
)

Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!

Get our RSS Feed!

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)