Guns
Guns

Reputation: 2728

Preg_Replace string between two strings

I have a string

<img alt="cid:[email protected]" src="image021.gif" id="Picture_x0020_1" border="0" height="26" width="156">

and i wish to replace cid:[email protected] with image037.gif.

I know this could be done with strpos and substr, however, out of my curiosity wanted to know how could this be achieved with regex.

Also, would be great if anyone here could help me with some good articles, tips and tricks on Regex or anything that helps us to understand how to learn regex.

Upvotes: 1

Views: 2582

Answers (3)

Sabuj Hassan
Sabuj Hassan

Reputation: 39443

considering the pattern will not be found inside the free text(means outside html tags).

print preg_replace('/"cid:(.+)@[a-zA-Z0-9\.]+"/', '$1', $string);

Upvotes: 1

Glavić
Glavić

Reputation: 43582

Try:

echo preg_replace('~<img(.+?)alt="cid:(.+?)@.+?"(.*?)>~', '<img$1alt="$2"$3>', $string);

Demo.

A good website, where you can learn and practice regex is regex101.com. See your explanation there. You also have quiz test which you can tryout.

Upvotes: 2

Stephan
Stephan

Reputation: 43083

Try this:

echo preg_replace('#<img(.+?)alt="[^:]+:([^@]+)@[^"]+"(.*?)>#', '<img$1alt="$2"$3>', $string);

Regular expression visualization

Upvotes: 2

Related Questions