tags:

views:

56

answers:

5

If I have a string in the following format: location-cityName.xml how do I extract only the cityName, i.e. a word between - (dash) and . (period)?

+3  A: 

Combine strpos() and substr().

$filename = "location-cityName.xml";

$dash = strpos($filename, '-') + 1;
$dot = strpos($filename, '.');

echo substr($filename, $dash, ($dot - $dash));
Rin
+3  A: 

Try this:

$pieces = explode('.', $filename);
$morePieces = explode('-', $pieces[0]);
$cityname = $morePieces[1];
Jeremy
Hmm, would it make it easier if I had the following format: cityName-location.xml ? Than I'll just need to strip anything startin with dash, right?
santa
I think it would be easier. In that order you could just use a combination of substr() and strpos() to get the city name, like $city = substr($filename, 0, strpos($filename, '-'));
Jeremy
+1  A: 

There are a few ways... this one is probably not as efficient as the strpos and substr combo mentioned above, but its fun:

$string = "location-cityName.xml";
list($location, $remainder) = explode("-", $string);
list($cityName, $extension) = explode(".", $remainder);

As i said... there are lots of string manipulation methods in php and you could do it many other ways.

Andy Groff
+1  A: 

Here's another way to grab the location as well, if you want:

$filename = "location-cityName.xml";
$cityName = preg_replace('/(.*)-(.*)\.xml/', '$2', $filename);
$location = preg_replace('/(.*)-(.*)\.xml/', '$1', $filename);
shoebox639
+1  A: 

Here is a regular-expression–based approach:

<?php
$text = "location-cityName.xml";
if (preg_match("/^[^-]*-([^.]+)\.xml$/", $text, $matches)) {
  echo "matched: {$matches[1]}\n";
}
?>

This will print out:

matched: cityName
Jeremy W. Sherman