Jump to content

Extract a string, modify it and save it back


Rootbeer

Recommended Posts

Here is what I Am trying to do:

  • Fetch an RSS feed and save it on my server
  • Find all the images in the feed (in the description field
  • Find out the size of the images, calculate a new size keeping the same aspect ratio
  • Update the height/width field of the image in the original feed

 

Heres what I have done so far:

  • Saved the feed in my server
  • Found all the images using preg_match_all()
  • Extracted the image URL using preg_match()
  • Calculated the new size

 

Now how do I update the feed saved in the server? Seems like I have to find the <img> tags again in the feed using regexp and replace them with the new updated <img> tags.

 

I feel like this is not the best way to do it. Can anyone help me out with a more efficient way?

 

Thanks!

 

p.s. Heres my code:

// Now find and resize image
$regex  = '#<img.*src=\".*\"\s\/>#';
preg_match_all($regex, $text, $matches);

foreach($matches[0] as $value)
{
                // Extract the image url from the <img> tag
	$regex = '#http:\/\/www\.website.com\/.*\.(jpg|jpeg|gif|png)#';
	preg_match($regex, $value, $imgurl);

               // Edit $value here. Now want to put $value back into $text
               // Now run another regexp here searching $text for old $value and replace it with the new $value?
}

Link to comment
Share on other sites

look into preg_replace_callback.  It can extract data and replace it with something else as it finds it, and you can supply a function to be called (passing the extracted info, returning what to replace) each iteration, so you can perform your calculations in the callback function (or call some other function that does it, w/e).

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.