skip to Main Content

I am reading the contents of some files with file_get_contents
the files contain a series of links and images. Ideally, they should all look like this.
The link and image will always be the same matching 8 digit numbers like this…

<a href='/item/33333333'>
<img src="https://www.example.com/33333333.gif"></a>

<a href='/item/12345678'>
<img src="https://www.example.com/12345678.gif"></a>

Sometimes an error image will show up instead of the url to the gif. Here’s the contents of a file with that error occurring twice…

<a href='/item/77778888'>
<img src="/images/default.svg"></a>

<a href='/item/33333333'>
<img src="https://www.example.com/33333333.gif"></a>

<a href='/item/12345678'>
<img src="https://www.example.com/12345678.gif"></a>

<a href='/item/22225555'>
<img src="/images/default.svg"></a>

So, I need my end result to be

<a href='/item/77778888'>
<img src="https://www.example.com/77778888.gif"></a>

<a href='/item/33333333'>
<img src="https://www.example.com/33333333.gif"></a>

<a href='/item/12345678'>
<img src="https://www.example.com/12345678.gif"></a>

<a href='/item/22225555'>
<img src="https://www.example.com/22225555.gif"></a>

I’m not sure how to go about figuring out what 8 digit number appears before each default.svg and replacing it. Would we have to look back a certain number of characters each time default.svg appears to get that number?

Thanks

2

Answers


  1. if that file is .php maybe u should store the home path in some variable, like laravel or yii2 do (home_url = $HOME), or make it hard coded.

    in the final should be:

    // Define variables
    $itemNumber = '77778888';
    $imageUrl = 'https://www.example.com/' . $itemNumber . '.gif';
    ?>
    <a href='/item/<?php echo $itemNumber; ?>'>
        <img src="<?php echo $imageUrl; ?>">
    </a>```
    
    Login or Signup to reply.
  2. Something like

    if (preg_match_all('@<as+href='/item/(d{8})'>s+<img@', $fileContent, $matches)) {
        foreach ($matches[1] as $id) {
            echo "<a href='/item/$id'>n<img src='https://www.example.com/$id.gif'></a>nn";
    }
    

    But I’m afraid that image https://www.example.com/77778888.gif may not exist

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search