Hello, coders! 💻
Here's another quick quiz.
Using PHP, how would you extract 878
from the string below?
$confFile = '/etc/nginx/sites-enabled/878.test.mysite.com.conf';
Here’s a possible solution that leverages type juggling.View my solution
$confFile = '/etc/nginx/sites-enabled/878.test.mysite.com.conf';
$number = (int) basename($confFile);
basename
removes everything before the rightmost /
and returns 878.test.mysite.com.conf
.
Then by taking advantage of PHP’s type juggling we convert that string to an int and are left with 878
.
Happy coding! ⌨️
Top comments (3)
<?php
$confFile = '/etc/nginx/sites-enabled/878.test.mysite.com.conf';
if(preg_match('/\d+/',$confFile,$arr)){
echo $arr[0];
}
?>
Other ways to extract numbers from strings in PHP
The first method, using regular expressions:
function findNum($str=''){
$str=trim($str);
if(empty($str)){return '';}
$reg='/(\d{3}(.\d+)?)/is';//Regular expression matching numbers
preg_match_all($reg,$str,$result);
if(is_array($result)&&!empty($result)&&!empty($result[1])&&!empty($result[1][0])){
return $result[1][0];
}
return '';
}
The second method, using the in_array method:
function findNum($str=''){
$str=trim($str);
if(empty($str)){return '';}
$temp=array('1','2','3','4','5','6','7','8','9','0');
$result='';
for($i=0;$i<strlen($str);$i++){
if(in_array($str[$i],$temp)){
$result.=$str[$i];
}
}
return $result;
}
The third method, using the is_numeric function:
function findNum($str=''){
$str=trim($str);
if(empty($str)){return '';}
$result='';
for($i=0;$i<strlen($str);$i++){
if(is_numeric($str[$i])){
$result.=$str[$i];
}
}
return $result;
}
You should wrap your code with triple backticks so it’s more readable.
Out of the three methods you posted the first one makes the most sense but the others are a fun take!
You can simplify your first
findNum
from:to
Thanks for your answer!
allgoodsfree.com/how-to-extract-th...