提取文件名的一部分

3
如果我有一个以下格式的字符串:location-cityName.xml,我如何提取cityName,也就是在破折号和句点之间的单词?
5个回答

4

试试这个:

$pieces = explode('.', $filename);
$morePieces = explode('-', $pieces[0]);
$cityname = $morePieces[1];

我认为这样会更容易。按照这个顺序,您可以使用substr()和strpos()的组合来获取城市名称,例如$city = substr($filename, 0, strpos($filename, '-')); - Jeremy

3

结合使用strpos()substr()函数。

$filename = "location-cityName.xml";

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

echo substr($filename, $dash, ($dot - $dash));

1

有几种方法...这个可能不如上面提到的strpos和substr组合那么高效,但它很有趣:

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

就像我说的…在PHP中有很多字符串操作方法,你还可以用其他方式实现。


1

如果你想的话,这里还有另一种获取位置的方法:

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

1
这是一个基于正则表达式的方法:
<?php
$text = "location-cityName.xml";
if (preg_match("/^[^-]*-([^.]+)\.xml$/", $text, $matches)) {
  echo "matched: {$matches[1]}\n";
}
?>

这将打印出:

matched: cityName

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接