如果我有一个以下格式的字符串:location-cityName.xml,我如何提取cityName,也就是在破折号和句点之间的单词?
试试这个:
$pieces = explode('.', $filename);
$morePieces = explode('-', $pieces[0]);
$cityname = $morePieces[1];
结合使用strpos()
和substr()
函数。
$filename = "location-cityName.xml";
$dash = strpos($filename, '-') + 1;
$dot = strpos($filename, '.');
echo substr($filename, $dash, ($dot - $dash));
有几种方法...这个可能不如上面提到的strpos和substr组合那么高效,但它很有趣:
$string = "location-cityName.xml";
list($location, $remainder) = explode("-", $string);
list($cityName, $extension) = explode(".", $remainder);
就像我说的…在PHP中有很多字符串操作方法,你还可以用其他方式实现。
如果你想的话,这里还有另一种获取位置的方法:
$filename = "location-cityName.xml";
$cityName = preg_replace('/(.*)-(.*)\.xml/', '$2', $filename);
$location = preg_replace('/(.*)-(.*)\.xml/', '$1', $filename);
<?php
$text = "location-cityName.xml";
if (preg_match("/^[^-]*-([^.]+)\.xml$/", $text, $matches)) {
echo "matched: {$matches[1]}\n";
}
?>
这将打印出:
matched: cityName