tags:

views:

35

answers:

2

Hi, I want to replace every link I find within a string, with a modified version of the string, say for example:

The quick brown fox jumped over the http://www.google.com/?v=abc and http://www.google.com/?v=x_y-z
I would replace (and modify) the links in this so it becomes: http://www.google.com/v/abc and http://www.google.com/v/x_y-z

I know how to find all the links using preg_match_all($pattern, $text, $out, PREG_SET_ORDER); and I can manipulate the strings using preg_split etc - This is done one at a time.

The outcome I'm looking for is:

The quick brown fox jumped over the http://www.google.com/v/abc and http://www.google.com/v/=x_y-z
However how could I match and replace all of them? Any help would be greatly appreciated.

+2  A: 

Use preg_replace for that:

$str = preg_replace('/\?v=([^ ]*)/', '/v/$1', $str);

This assumes that you want to match everything after ?v= and put it after the /v/. If that's not the case, you'll have to be more specific about what the pattern is.

VoteyDisciple
Preg_replace only works on the first instance it find, I want it to work on all instances.
john mossel
No, preg_replace works on all instances; the question is just what the pattern matches. I've edited my answer to include a more specific pattern — only counting text up to the next whitespace.
VoteyDisciple
Ah, yes you are correct. Say for example now that you have a two URIs such as http://www.site.com/watch?v=xyz and http://www.site.com/?v=abc, how would you match both of these (knowing that watch is optional). Both of these should be replace with http://www.site.com/v/xyz and http://www.site.com/v/abc
john mossel
+1  A: 

using the g (global) and i (case insensitive) flags should extend the search to everything.

$string = preg_replace('/\?v=([^\s]+)/gi','/v/$1', $string);

This assumes that there is some type of whitespace after your url.

Jesse
Hi, what would you do if the url was something like http://www.site.com/abc?v=xyz -- How would you make the abc? part go away .i.e so the URI becomes http://www.site.com/v/xyz and not http://www.site.com/watch/v/xyz
john mossel
Unknown modifier 'g' is what I get when I try that.
john mossel
ah, it looks like preg_replace is inherently global. as for your question, in php, it would look like this: preg_replace('/\/[^\?/]+\?([^=]+)=([^\s]+)/', '/$1/$2', $string); - this would also match site.com/foo?bar=baz and return site.com/bar/baz
Jesse