1

Thanks to @s.d.a.p.e I've come a step close but I'm not quite there yet.

What I'm trying to do is replace all instances of a string in a block of text. I want to replace something like this:

user is ?user_id=34&first_name=Ralph so is ?user_id=1 also

With this:

user is /user/34/ so is /user/1/ also

Here is the preg_replace code I'm using:

$pattern = '#\?user_id=([0-9]+)#';
$replace = '/user/$1/';
echo preg_replace($pattern,$replace,$string);

With that pattern I end up with this:

user is /user/34/&first_name=Ralph so is /user/1/ also

Thanks again.

5
  • anything you tried already? Commented Apr 16, 2015 at 20:40
  • @RST, yes. I was actually going through my history finding close examples. I'll get those posted in a few minutes. Commented Apr 16, 2015 at 20:41
  • print preg_replace('#\?user_id=([0-9]+)\&(first_name=(?:.*))#','/user/$1?$2','?user_id=34&first_name=Ralph'); Commented Apr 16, 2015 at 20:57
  • I've update my answer, it works as you want. Commented Apr 18, 2015 at 4:52
  • preg_replace('~\?user_id\=(\d+)\S*~i', '/user/$1/', $string); Commented Apr 18, 2015 at 5:48

3 Answers 3

1

try this:

$string = "user is ?user_id=34&first_name=Ralph so is ?user_id=1 also";
$result = preg_replace('/\?(user)_id=(\d+)(.*?)(?! )/i', '/$1/$2/$3', $string );

echo $result ;

Output:

user is /user/34/&first_name=Ralph so is /user/1/ also

DEMO

Sign up to request clarification or add additional context in comments.

Comments

1

I'd use this:

$string = 'user is ?user_id=34&first_name=Ralph so is ?user_id=1 also';
$pattern = '#\?user_id=([0-9]+)\S*#';
$replace = '/user/$1/';
echo preg_replace($pattern, $replace, $string);

Where \S stands for any character that is not a space.

Output:

user is /user/34/ so is /user/1/ also

Comments

1
print preg_replace(
   '#\?user_id=([0-9]+)\&(first_name=(?:.*))#',
   '/user/$1?$2',
   '?user_id=34&first_name=Ralph'
);

result :

/user/34?first_name=Ralph  if get it right..

2 Comments

for /user/34 remove ?$2
This is extremely close, but when I remove ?$2, it doesn't continue on with the string and stops at /user/34. "user is ?user_id=34&first_name=Ralph and hes a user." is the

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.