Function to return only alpha-numeric characters from string?

To return only alpha-numeric characters from a string in PHP, you can use the preg_replace function with a regular expression pattern that matches any non-alphanumeric character. Here's an example:

<?php

function keep_alphanumeric($string) {
  return preg_replace("/[^a-zA-Z0-9]/", "", $string);
}

This function will take a string as input and return a new string with all non-alphanumeric characters removed.

Watch a course Learn object oriented PHP

For example:

<?php

function keep_alphanumeric($string)
{
  return preg_replace("/[^a-zA-Z0-9]/", "", $string);
}

echo keep_alphanumeric("Hello, World! 123") . PHP_EOL; // Outputs "HelloWorld123"
echo keep_alphanumeric("Fo0-BaR"); // Outputs "Fo0BaR"