Get only part of string
-
02-01-2020 - |
Domanda
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.
Soluzione
$newString = preg_replace('/\D/', '', $myString);
The regular expression \D
matches anything that isn't a digit. This replaces them all with nothing.
Altri suggerimenti
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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow