We participate in the Amazon Service LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com

preg_match problem

Given:

$a = "4|6|3|5|x|2|";

Write code that will output:

“2|3|4|5|6”

It could be done the long way round, by turning the string into an array, looping over each element, testing each item to see if it’s a number, and placing the numbers in another array, then sorting that array, then turning the array back into a string. (whew) But there is a better way.

$a = "4|6|3|5|x|2|";

// empty array to hold matches
$matches = array(); 

// convert $a to array, then look for digits using regex
preg_match('/\d+/', explode('|', $a), $matches); 

// sort array, then turn back into string delimited with pipes
echo implode('|', sort($matches[0]));