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])); 

 

Leave a Reply

Your email address will not be published. Required fields are marked *