Search code examples
phppreg-matchstr-replacestrpos

PHP str_replace or preg_match or strpos when specific string plus if integer


I am trying to remove the two strings and two integers from a URL string if there is a specific match, for example from those WP generated featured image crop URLS:

http://website.com/uploads/image1-150x150.jpg
http://website.com/uploads/image2-300x160.jpg

Basically I want to be left with:

http://website.com/uploads/image1.jpg
http://website.com/uploads/image2.jpg

I therefore need to check, if the URL has the order of a minus "-", then an INT, then the letter "x", then again an INT, before the .jpg ending. If so, then it should remove all of that.

What is the best way and how would I need to do it? preg_replace or str_replace or strpos?


Solution

  • preg_replace() is the appropriate function for this.

    $str = preg_replace('/-\d+x\d+\.jpg$/', '.jpg', $str);