What are best practices for sorting strings with numbers in PHP arrays to ensure accurate sorting?

When sorting strings with numbers in PHP arrays, it's important to use a custom sorting function that takes into account the numerical values within the strings. One approach is to use a regular expression to extract the numeric portion of each string and compare them numerically during the sorting process. This ensures that the strings are sorted accurately based on their numerical values rather than just their string representation.

$strings = ["item1", "item10", "item2", "item20", "item3"];

usort($strings, function($a, $b) {
    preg_match('/(\d+)/', $a, $matchesA);
    preg_match('/(\d+)/', $b, $matchesB);

    return intval($matchesA[0]) - intval($matchesB[0]);
});

print_r($strings);