Regex and Json

Hello i have a an application that needs to decide whether to treat a flow of structured data as json or as xml tree based on an anlysis of an url that it calls that should ends by .json or .xml

i have this piece of code, does that do the trick?

if (preg_match(‘#\.([^\.])$#’, $url, $format)) {
$format = $format[1];
} else {
$format = ‘xml’;

thanks in advance


$extension = end(explode(‘.’,$url));

seems easier to me :wink:

Your pattern seems to be correct, though i’m not sure why you’d ever need the else… if a file doesnt end in an extension, you’re running either an index file or a script - neither of which would be an XML?

thank you i didn’t see that, i think your solution seems easier than doing into the regex game…

There are also specific tools available for working with URLs and file paths, to save you needing to use regex/string functions.

$extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);