DEV Community

Julien Dephix
Julien Dephix

Posted on

1 1

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 β€’

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay