Mini challenge: PHP
Julien Dephix

Julien Dephix @joolsmcfly

About: Been programming for over 20 years and loving it!

Location:
France
Joined:
Jun 24, 2022

Mini challenge: PHP

Publish Date: Jun 28 '22
2 3

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! ⌨️

Comments 3 total

  • leichengde
    leichengdeJul 2, 2022

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

    • Julien Dephix
      Julien DephixJul 2, 2022

      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!

Add comment