Search code examples
phpwhile-loopstrpos

Checking a string contains multiple pieces of text


I'm developing a news site, and am allowing the authors of any articles to decide how many images they'd like to add within the article.

To include the image they need to input [image1] within the body of the article content, which is then converted into the image src on another page.

I'm attempting to write a piece of code that checks how many images the user has input, along with accompanying captions, then see if they have applied the [image#] and [caption#] tags for each.

Desired functionality:

If the user has chosen to upload two images for the article, they must also insert two captions. They must then state [image1][caption1] and [image2][caption2] wherever they desire within the article's content.

If the user has posted the images and the captions into the form, however have not included the correct number of [image#] and [caption#], I'm looking to prompt them into doing so using strpos(). However am struggling to achieve this.

Here is my code thus far, if anyone could show me what I'm doing wrong it'd be appreciated.

Cheers, Rich

$z = 1;
while($z < $caption){
if (strpos($articleContent,'[caption$z]') == !false) {
echo 'You have added all of your caption tags in the article.';
$z++;
} else {
echo "You have not added all of your [caption#] tags in the article content.";
exit(); 
}
}

I'm then looking to simply C&P the same to count the [image#] tags.


Solution

  • So after a week of trying to solve this, I think I'd best share the answer as there seems to be a lack of people attempting to do the same.

    Solution:

    $articleContent = $_POST['articleContent'];
    $imgCount = count($imgTmp1); // Count files array
    $capCount = count($captions); // Count captions array 
    $r = 0;
    $c = 0;
    
    while($r < $imgCount){
    
    $i = 1;
    $z = 1;
    $r++;
    $c++;
    
    $value = "[image$r]";
    for($check = strpos($articleContent,$value);$i<$imgCount;$i++){
    }
    if($check !== false){
    // Your success, if any
    } else {
    echo "<span class='error'>You need to include '$value' into the article content.</span>";
    exit();
    }
    
    $value2 = "[caption$c]";
    for($check2 = strpos($articleContent,$value2);$z<$capCount;$z++){
    }
    
    if($check2 !== false){
    // Your success, if any
    } else {
    echo "<span class='error'>You need to include '$value2' into the article content.</span>";
    exit();
    }
    }
    

    The issue wasn't with the variables themselves, as they were echoing out correctly in every loop I attempted the check with. The issue was actually with the strpos. As you can see, I've inserted the strpos within the loop itself and it works like a peach.

    Good luck to anyone else struggling with the same issue I have here, thanks to everyone else for their help too.