Thanks again @clarkwinkelmann
One huge Array and a step down into the preg_replace_callback()-hell later, this seems to work.
The following creates an Array with all post-IDs and the determined posts.number:
// Create an array for all posts, to save the determined Flarum posts.number to link to
$sql = <<<SQL
SELECT m.ID_TOPIC, m.ID_MSG
FROM `smf_messages` m
ORDER BY m.ID_TOPIC, m.posterTime
SQL;
$posts = $smf->query($sql);
$posts->setFetchMode(PDO::FETCH_OBJ);
// determine posts.number
$postsNumber = array();
$currentTopic = null;
while ($post = $posts->fetch()) {
if ($currentTopic != $post->ID_TOPIC) {
$currentTopic = $post->ID_TOPIC;
$number = 0;
}
$postsNumber[$post->ID_MSG] = ++$number;
}
// print_r($postsNumber);
The following function get's called for every single post:
/**
* Convert old internal SMF URLs to new Flarum URLs
*/
function convertInternalLinks($str)
{
// prepare smf_url for regular expressions
$smfUrl = str_replace('https', 'https?', preg_quote(smf_url, "/"));
// https://example.com/community/index.php?topic=27160.0
// https://example.com/community/index.php?topic=27999.msg343450#msg343450
$regexp = '/'.$smfUrl.'index.php\?(topic=(\d+))+(\.(msg|d*)(\d+))*+(\#msg\d+)*/is';
if (preg_match_all($regexp, $str, $matches)) {
$str = preg_replace_callback(
$regexp,
function ($matches) {
global $postsNumber;
// print_r($matches);
if (array_key_exists('5', $matches) && $matches[5] != 0) {
return fla_url."d/".$matches[2]."/".$postsNumber[$matches[5]];
} else {
return fla_url."d/".$matches[2];
}
},
$str
);
}
return $str;
}