1

My problem is I'm trying modifying a Wordpress plugin (Comic Easel) without complete knowhow of PHP. Anyway, what I wanted to do is make mobile/vertical versions of my comic strip (cause mine is in horizontal format), so I made alternate versions of the comic images, say http://example.com/comic1m.jpg

Now here's the code:

$thumbnail = wp_get_attachment_image_src( $post_image_id, $size, false);

What this does is get the URL of the image attached to a post, and make a variable out of it. For example, $thumbnail would now be:

$thumbnail = "http://example.com/comic1.jpg"

What I want to do is assign another $mthumbnail using wp_get_attachment_image_src like with $thumbnail, except with the m added on at the end (or replace the last 4 characters) so http://example.com/comic1.jpg turns into http://example.com/comic1m.jpg

$thumbnail = "http://example.com/comic1.jpg"
$mthumbnail = "http://example.com/comic1m.jpg"

Another problem is the image URLs could have different lengths and file formats, so I thought that just replacing the last 4 characters is the better solution. If there's a way to code it so that it can tell the file formats apart, remove/replace the strings, and then add the m and file format back that'd be great.

  • Possible duplicate of [Remove the last character from string](https://stackoverflow.com/questions/5592994/remove-the-last-character-from-string) – Alessandro Da Rugna Apr 06 '19 at 18:50

1 Answers1

0

You could match the dot and the extension (1+ word characters using \w+ or jpg exactly) at the end of the string.

Then you might use preg_replace and replace with m$0 where $0 refers to the full match.

$thumbnail = "http://example.com/comic1.jpg";
$mthumbnail = preg_replace('/\.\w+$/', "m$0", $thumbnail);
echo $thumbnail; // http://example.com/comic1m.jpg

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • 1
    Oh wow it worked, thanks so much! Though now the problem is if a webpage loads when it's lower than 1000px, it attempts to load the file even when it doesn't exist (yet), so it just shows a broken image. But you've solved the problem, so thanks again! I'll just ask another question here in stackoverflow then. – Lazylonewolf Apr 06 '19 at 19:16