这是来自数据库“ fishPrice / 1572268723Career Portal.pdf”的示例URL,我只想打印文件名,即“ Career Portal”,什么是最好的方法?
我尝试使用“ preg_match”,但出现“未定义的偏移量错误”
$ fishPrice ['price']包含网址
<?php
if(!empty($fishPrices))
{
foreach ($fishPrices as $fishPrice)
{
$date = strtotime($fishPrice['Date']);
$url = $fishPrice['price'];
$pattern = "[0-9]/";
preg_match('[0-9]', $url, $matches);
$price = $matches[1];
?>
<div class="">
<div class="col-lg-6 col-lg-offset-0 col-md-8 col-md-offset-2 col-sm-12">
<div class="container-outer">
<div class="container-inner ">
<div class="images-left">
<img src="http://via.placeholder.com/270x270" alt="girl-heart">
</div>
<div class="text-cont-right">
<div class="images-text">
<h3><a href="features-ecology.html"><?= date('M j Y', $date)?></a></h3>
<p><?= $price ?></p>
</div>
<div class="buttons">
<a href="admin/<?=$fishPrice['price']?>" class="green-btn green-btn-news">Read More</a>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
感谢您的任何帮助
一种方法,将preg_match
与捕获组一起使用:
$input = "fishPrice/1572268723Career Portal.pdf";
preg_match("/.*\d{10}(.*)\.\w+$/", $input, $matches);
echo $matches[1];
此打印Career Portal
。此处的正则表达式逻辑是捕获最后10位数字序列之后但文件扩展名之前的所有内容。
好的,我为您制作了一个小例子。
$string = "fishPrice/1572268723Career Portal.pdf";
//Echo 1572268723Career Portal.pdf
$string = substr($string, strpos($string, "/")+1);
while(is_numeric($string[0]))
{
$string = substr($string, 1);
}
//Career Portal.pdf
echo $string;
首先,我将/的子字符串始终放在您所说的位置。此后,我将削减数字,直到得到一个有效的字符,这将是名称的开头。希望能有所帮助!
仅使用一个样本字符串,图案精度是推测性的。
我最好的猜测是:
$input = "fishPrice/1572268723Career Portal.pdf";
echo preg_match("~\d{10}\K[^.]+~", $input, $out) ? $out[0] : 'fail';
仅匹配10位数字后的非零字符。