DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Julien Dephix
Julien Dephix

Posted on

Mini challenge: PHP

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';
Enter fullscreen mode Exit fullscreen mode

View my solution

Here’s a possible solution that leverages type juggling.

$confFile = '/etc/nginx/sites-enabled/878.test.mysite.com.conf';
$number = (int) basename($confFile);
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
leichengde profile image
leichengde

<?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;
}

Collapse
 
joolsmcfly profile image
Julien Dephix

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:

if (is_array($result) && !empty($result) && !empty($result[1]) && !empty($result[1][0])) {
    return $result[1][0];
}
return '';
Enter fullscreen mode Exit fullscreen mode

to

return $result[1][0] ?? β€˜β€™;
Enter fullscreen mode Exit fullscreen mode

Thanks for your answer!

Collapse
 
leichengde profile image
leichengde

Timeless DEV post...

How to write a kickass README

Arguably the single most important piece of documentation for any open source project is the README. A good README not only informs people what the project does and who it is for but also how they use and contribute to it.

If you write a README without sufficient explanation of what your project does or how people can use it then it pretty much defeats the purpose of being open source as other developers are less likely to engage with or contribute towards it.