PHP preg replace only allow numbers

You can use the preg_replace() function in PHP to only allow numbers in a string using a regular expression. The regular expression to match only numbers is /[^0-9]/, which means "match any character that is NOT a number between 0 and 9". To use this in preg_replace(), you would call it like this:

<?php

$original_string = "abc123def456";
$only_numbers = preg_replace("/[^0-9]/", "", $original_string);
echo $only_numbers;

Watch a course Learn object oriented PHP

This will replace any non-numeric characters in the original string with an empty string, effectively only allowing numbers to remain.