PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How to Programmatically Prefix an Image URL with PHP?

 November 20, 2022     filenames, php, preg-replace, regex, url-rewriting     No comments   

Issue

I'm working with PHP and a JSON-based API that returns 2 fields with values for property photos:

  1. photo_url
  2. has_large

The photo_url is the regular sized photo URL.

Example: https://secure.example.org/Directory/AnotherDirectory/0008/102/12.jpg

If has_large = true, then we know a large photo exists, but the API doesn't return the specific URL.

However, from the API documentation, we know that if we prefix the image filename with a 'L', this gives us the correct large image URL:

Example: https://secure.example.org/Directory/AnotherDirectory/0008/102/L12.jpg

How can I programmatically prefix the filenames with the letter L, before writing them to the database (MySQL)?

Note: The URL structure is nearly the same for all photos.

The only parts of the image URLs that change for each property are:

  1. The 4th level directory which specifies property ID (In the example above -- 102)
  2. The filename itself, which is a maximum of 3 numbers (In the URL example above -- 12.jpg).

After hours of research on RegEx, preg_replace() and looking for similar solutions on StackOverflow, I'm still not sure how to accomplish this correctly using PHP.

Any help would be appreciated. Thanks in advance.


Solution

It seems you only need to prepend a file name (without path) with L. A file name without path is anything but / in at the end of string, which in regex looks ([^\/]+)$. Therefore the desired replacement function is:

$large_photo_url = preg_replace('/([^\/]+)$/', 'L$1', $photo_url);


Answered By - Dmitry Egorov
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing