tags:

views:

57

answers:

3

I've got a piece of text that contains another regular expression.

Sample text:

...<rege>!^.*$!mailto:[email protected]!</rege>...

What I want to match is:

mailto:[email protected]

This didn't work:

 $patterns[] = '/<rege>!\^\.\*\$!(.*)!<\/rege>/';

Thoughts?

A: 

Try with this:

$patterns[] = '/<rege>!\^\.\*\$!([^<]*)!<\/rege>/';
mck89
A: 

To have \ inside '' you have to double it like so:

$patterns[] = '/<rege>!\\^\\.\\*\\$!(.*)!<\\/rege>/';

I also think that you may want this match to be ungreedy because you want to properly capture email even if similar constructs occur in search text multiple times so:

$patterns[] = '/<rege>!\\^\\.\\*\\$!(.*?)!<\\/rege>/';
Kamil Szot
??? That's not true and if it was it would be for double quoted strings, not single quoted as used by Steve.
p4bl0
hm.. you are right, it seems that doubling backslash to obtain literal backslash is only necessary before single quote or at the end of the string. But using double backslash anywhere else also gives only one backslash and is more consistent.
Kamil Szot
I tried the second one and it worked just fine! Thanks Kamil!!
Steve
A: 

You need to escape your backslashes:

<?php

$sample = "<rege>!^.*$!mailto:[email protected]!</rege>";
preg_match("/<rege>!\\^\\.\\*\\$!(.*)!<\/rege>/",$sample,$matches);

print_r($matches);
?>
Vinko Vrsalovic