0

here's my question:

i have the folwing code in my project:

$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>";

What i want is to display the number of the news part, but the problem is that there are articles with +20/+30 parts and i don't want to add

else if(strpos($news,'.part20')) {$news_n = ".part20";}

etc to my code.

Is there any easier way to do this?

Thanks in advance for your help!

4 Answers 4

2

you can use PHP preg_match for this

$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>";

Edit: You can also use $new_n = $matches[0];. $matches[0] gives you the full match and $matches[1] will have the number part.

Edit2: If the .part is the going to be the last item, then you can use much simpler strstr.

$news = "Article 20.part20";
$news_n = strstr($news, ".part");   
echo $news;
echo "Part number:" . $news_n . "- <a href=\"#\">Read more</a>";
Sign up to request clarification or add additional context in comments.

1 Comment

This is the best solution, but maybe he need to think about loops before go to regexp
1

Maybe something like:

for($i=1;$i<100;$i++)
{
    if(strpos($news,'.part'.$i)) 
        $news_n = '.part'.$i;
}

Comments

1

Use a regular expression

$matches=[];
if (preg_match_all('.part\[( ^[0-9]{1,3}$)\]/', $news, $matches)) {
print_r($matches);
}

Comments

0

If the string you are looking for is numbered based as you say in your question you can do:

foreach(range(1, 50) as $i) {
    $part = sprintf('.part%d', $i);
    if(strpos($news, $part) {
        $news_n = sprintf('.%s', $part);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.