这是我的问题:
我的项目中有以下代码:
$news = "Article 20.part2";
if(strpos($news,'.part1')) {$news_n = ".part1";}
else if(strpos($news,'.part2')) {$news_n = ".part2";}
else if(strpos($news,'.part3')) {$news_n = ".part3";}
else if(strpos($news,'.part4')) {$news_n = ".part4";}
else if(strpos($news,'.part5')) {$news_n = ".part5";}
echo $news;
echo "Part number:" . $news_n . "- <a href='"#'">Read more</a>";
我想要的是显示新闻部分的编号,但问题是有+20/+30部分的文章,我不想添加
else if(strpos($news,'.part20')) {$news_n = ".part20";}
等等到我的代码。
有什么更简单的方法吗?
提前感谢您的帮助!
您可以将PHP preg_match用于此
$news = "Article 20.part20";
$matches= array();
if (preg_match("/'.part('d*)/", $news,$matches)){
$news_n = '.part'. $matches[1];
}
echo $news;
echo "Part number:" . $news_n . "- <a href='"#'">Read more</a>";
编辑:您也可以使用$new_n = $matches[0];
。$matches[0]
为您提供完全匹配,$matches[1]
将具有数字部分。
Edit2:如果.部分将是最后一项,那么您可以使用更简单的strstr。
$news = "Article 20.part20";
$news_n = strstr($news, ".part");
echo $news;
echo "Part number:" . $news_n . "- <a href='"#'">Read more</a>";
也许类似于:
for($i=1;$i<100;$i++)
{
if(strpos($news,'.part'.$i))
$news_n = '.part'.$i;
}
使用正则表达式
$matches=[];
if (preg_match_all('.part'[( ^[0-9]{1,3}$)']/', $news, $matches)) {
print_r($matches);
}
如果你在问题中所说的字符串是基于编号的,你可以这样做:
foreach(range(1, 50) as $i) {
$part = sprintf('.part%d', $i);
if(strpos($news, $part) {
$news_n = sprintf('.%s', $part);
}
}