W3docs

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.

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:

Example of using the preg_replace() function in PHP to only allow numbers in a string

<?php

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

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

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