1

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.

2
  • 1
    How is the first string (the one you want to replace) generated? Does it always have exactly this form only another imagename, ...? Commented Nov 13, 2013 at 11:49
  • An entire HTML is generated once i scan an e-mail from an exchange inbox. the src and alt of the img tag will always start with cid: and will end with @ some alpha-numeric numbers Commented Nov 13, 2013 at 11:51

3 Answers 3

2

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.

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

5 Comments

Fails for: < img alt="cid:[email protected]" src="image021.gif" id="Picture_x0020_1" border="0" height="26" width="156" >
@TiMESPLiNTER: < img is invalid html tag.
Yep but how can you be sure that never occures one? What I try to say with that is that as more of the tag you're matching as bigger is the possbility that the regex fails on creepy tags.
@TiMESPLiNTER: I know what you are shooting at, but your example < img is just wrong, because that is not even a html tag, it is simply a string, like <strong>< img</strong>. Since your example will replace all alt=""'s in the code, my will only replace those of the <img> tag.
Thanks @Glavić! the link provided by you is awesome! Thanks for helping to learn! Stackoverflow Rocks!
2

Try this:

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

Regular expression visualization

3 Comments

Wow Alex! I love the way you have explained! Thanks a ton!
Alex: where did you get this picture? Is there somekind of website that generates images from regular expresions?
@Glavić Type your regex on Debuggex.com and there is an upper right link for exporting it here on SO.
1

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);

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.