0

As a regex newbie, this is frustrating me - all help appreciated. I have something like this:

<img src="https://jdfsdf.dsfsdf.sdfsd/upload/sm/dsfsdf/sdfsdf/sdfdsf.jpg" style="..." id="..">

I want it to be:

<img src="https://jdfsdf.dsfsdf.sdfsd/upload/lg/dsfsdf/sdfsdf/sdfdsf.jpg" style="..." id="..">

Basically, changing the /sm/ to /lg/. I'd like to do this via RegEx in PHP, and I'm using http://www.phpliveregex.com/ to test.

I could do this simply, but with less robustness, using a simple PHP str_replace - for the sake of this question I'd like to keep the answers using RegEx.

I have tried to use a look-behind, like below:

(?<=<img src.+upload\/)sm

This obviously doesn't work, but the code below does match to the desired point.

<img src.+upload\/

I'm stumped. Any assistance or links to a decent tutorial that covers this would be greatly appreciated.

3 Answers 3

6

You need to capture your result into a group. Your regex will look like this:

(<img src.+upload/)(sm)([^>]+>)

As you can see you can capture groups by adding parentheses. Now it's just the matter of using these groups and replacing the values.

$string = '<img src="https://jdfsdf.dsfsdf.sdfsd/upload/sm/dsfsdf/sdfsdf/sdfdsf.jpg" style="..." id="..">';
$pattern = '/(<img src.+upload/)(sm)([^>]+>)/i';
$replacement = '$1lg$3';
echo preg_replace($pattern, $replacement, $string);

Try this regex out at http://gskinner.com/RegExr/

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

2 Comments

Is that replacement pattern supposed to be '$1lg$3'? Great answer, btw.
Accepted this answer, but it does need an escape in the $pattern declaration: $pattern = '/(<img src.+upload\/)(sm)([^>]+>)/i'; Thank you.
1

Try this:

preg_replace('@(<img[^>]+http[^\'">]+)/sm/@i', '$1/lg/', $str1);

Comments

0

You can use str_replace for this. Regexp for this task is very hard.

Comments

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.