Php 提取部分文件名
如果我有以下格式的字符串:location-cityName.xml如何仅提取cityName,即介于-(破折号)和之间的单词。(句号)组合Php 提取部分文件名,php,regex,Php,Regex,如果我有以下格式的字符串:location-cityName.xml如何仅提取cityName,即介于-(破折号)和之间的单词。(句号)组合strpos()和substr() 试试这个: $pieces = explode('.', $filename); $morePieces = explode('-', $pieces[0]); $cityname = $morePieces[1]; 有几种方法。。。这个可能没有上面提到的strpos和substr组合那么有效,但它很有趣: $strin
strpos()
和substr()
试试这个:
$pieces = explode('.', $filename);
$morePieces = explode('-', $pieces[0]);
$cityname = $morePieces[1];
有几种方法。。。这个可能没有上面提到的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";
}
?>
我想这会容易些。按照这个顺序,您可以使用substr()和strps()的组合来获取城市名称,比如$city=substr($filename,0,strps($filename,“-”);
<?php
$text = "location-cityName.xml";
if (preg_match("/^[^-]*-([^.]+)\.xml$/", $text, $matches)) {
echo "matched: {$matches[1]}\n";
}
?>
matched: cityName