Anton Brix
Anton Brix

Reputation: 15

PHP RegEx - Remove from char to char?

I have this string:

http://scontent-b.xx.fbcdn.net/hphotos-prn2/t1/c22.0.100.100/p100x100/1489204_568091786618712_2075358603_n.jpg

I want to remove following part of the string:

c22.0.100.100/p100x100/

... But following part of the string is dynamic (changes):

c22.0.100.100

I'm thinking that it might be possible to use the PHP preg_ function in combination with a regular expression i some way? Example: Remove backwards from /p100x100/ to next / ??

Does anyone have a solution for this problem?

Upvotes: 1

Views: 121

Answers (4)

Toto
Toto

Reputation: 91385

How about:

preg_replace('~/c\d+(?:\.\d+){3}/p100x100\b~', '', $str)

Upvotes: 0

Nambi
Nambi

Reputation: 12042

Do like this to remove the c22.0.100.100/p100x100/

<?php
$str="http://scontent-b.xx.fbcdn.net/hphotos-prn2/t1/c22.0.100.100/p100x100/1489204_568091786618712_2075358603_n.jpg";

    echo preg_replace('~(?<=t1).*(?=\/)~',"",$str);

Demo

Upvotes: 0

Gavin Jackson
Gavin Jackson

Reputation: 2047

CODE:

  $a = 'http://scontent-b.xx.fbcdn.net/hphotos-prn2/t1/c22.0.100.100/p100x100/1489204_568091786618712_2075358603_n.jpg';;
  $b = preg_replace("/[^\/]*\/p100x100\//",'',$a);
  echo 'A: '.$a."\n";
  echo 'B: '.$b."\n";

This regex [^\/]*\/p100x100\/ replaces...

  • [^\/]* as many non-'/'
  • \/p100x100\/ followed by /p100x100/
  • '' with nothing

OUTPUT:

A: http://scontent-b.xx.fbcdn.net/hphotos-prn2/t1/c22.0.100.100/p100x100/1489204_568091786618712_2075358603_n.jpg
B: http://scontent-b.xx.fbcdn.net/hphotos-prn2/t1/1489204_568091786618712_2075358603_n.jpg

Upvotes: 1

Ben Green
Ben Green

Reputation: 438

preg_replace('¦/t1/.*/p100x100/¦', '/t1/', $string)

could throw some funny problems though using .* but without any other information on what the replaceable string could be it's the best that can be done.

what's your final aim of this? what does it do, what does it need to do, and why, these are all pieces of the puzzle that will help people answer :)

Upvotes: 0

Related Questions