user2028856
user2028856

Reputation: 3183

PHP Regex Remove Everything After Last Character In String

I have the following string of img url's which I'm trying to sanitize

$img_string = http://image.s5a.com/is/image/saks/0401694719016_647x329.jpg," "="">/-/http://image.s5a.com/is/image/saks/0401694719016_A1_647x329.jpg," "="">

I'm exploding the string first like this

$img_array = explode('/-/',  $img_string);

But I can't find a regex to remove everything after the last character in the image url.

e.g. regardless whether the img url ends in .png or .jpg or .jpeg, I need to just sanitize it. My expected output is

http://image.s5a.com/is/image/saks/0401694719016_647x329.jpg

instead of

http://image.s5a.com/is/image/saks/0401694719016_647x329.jpg," "="">

So my question is, can someone help me with the required regex to achieve this?

Thanks

Upvotes: 0

Views: 1096

Answers (4)

Sly
Sly

Reputation: 361

removing everything after the first comma like this :

$result = preg_replace('@[,].*$@ui', '', $img_string);

Upvotes: 0

Howl
Howl

Reputation: 1

Should work with this, deletes the comma from the URL:

if (preg_match_all("/(.*?),/is", $img_string, $matches)) {
  $url = $matches[1][0];
  echo $url;
}

Edit: tested here: http://ideone.com/pq1WzA

Upvotes: 0

vks
vks

Reputation: 67968

(?<=jpg|png|jpeg).*

Try this.Replace by empty string.See demo.

http://regex101.com/r/rQ6mK9/44

Upvotes: 1

anubhava
anubhava

Reputation: 784958

You can use preg_match using this regex:

[^,]+

RegEx Demo

Alternatively you can use this regex as well for preg_match:

^.+?\.(png|jpe?g)

Upvotes: 0

Related Questions