使用PHP preg_replace将标识符转换为吸引人的标题

For a small history oriented project I am looking to convert an identifier (used for links) to an appealing title. Below are five examples of how the identifiers might be called and how I am trying to make them look. However, I can't figure it out unfortunately.

Is there an elegant solution for something like this in PHP?

[identifier] = [title]

  • 1904 = 1904
  • 1904-1905 = 1904/05
  • 1904-1905-france = 1904/05 France
  • 1904-1905-france-germany = 1904/05 France Germany
  • 1904-1905-france-germany-spain = 1904/05 France Germany Spain

This should work for you:

Just use preg_replace_callback() to bring your string in your expected format, e.g.

<?php

    $str = "1904-1905-france-germany";
    echo $str = preg_replace_callback("/(\d+)(?:-(\d+))?(.*)/", function($m){
        if(!empty($m[2]))
            return $m[1] . "/" . substr($m[2], -2) . implode(" ", str_replace("-", " ", array_map("ucfirst",  explode("-", $m[3]))));
        return $m[1];
    }, $str);

?>

output:

1904/05 France Germany

Getting all elements into an array, and filtering and formatting result by array element counts works too:

   $subject2 = '1904-1905-france-germany-spain';

   $new = explode('-', $subject2);

if(count($new) == 2){ 

   echo $name = $new[0] . '/' . substr($new[1], 2);

} elseif (count($new) > 2) {

    $name = $new[0] . '/' . substr($new[1], 2);

        for($i = 2; $i<count($new); $i++ ){
            $name.= ' ' . ucfirst($new[$i]) . ' ';
         }
    $name = trim($name, ' ');
    echo $name;
}