Question

I have a string like this:

$myString = "line40";

Where the value 40 is variable (I have a set of random numbers).

I would like to get ONLY the number 40 (or any other random numer - 40 is just an example).

Just like this:

$newString = 40;

I tried to do using a regular expression but I failed... Please, someone can help me?

Thanks a lot.

Was it helpful?

Solution

$newString = preg_replace('/\D/', '', $myString);

The regular expression \D matches anything that isn't a digit. This replaces them all with nothing.

OTHER TIPS

try preg_match()

$myString = 'line40';
preg_match('/([0-9])+/', $myString, $m);
echo $m[0]; // 40

How about this, You can use filters

$myString = "line40";
$myString = filter_var($myString, FILTER_SANITIZE_NUMBER_INT);
echo $myString; //output: 40

Ref: http://php.net/manual/en/filter.filters.sanitize.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top