Jump to content

Conditional subpattern


lordfrikk

Recommended Posts

Hey,

 

I was working on kinda complex regex lately, I have it done now, but I was wonderin if there was a way to minify the code.

 

Here's that I was pondering about:

 

Sample text:

 

<a href="LINK">LINK</a>

 

And sample pattern:

 

_(?:<a href=")?(LINK)(?:">)?/1(?:<\/a>)?_i

 

Explanation:

 

I only wanna grab LINK, thus :? (non-capturing parentheses). I want this to apply to LINK and also to <a href="LINK">LINK</a> so I put those tag parts in optional parentheses ()?. What I was wondering is, if there is way to say to the regex engine, if it didn't match (<a href=")? it doesn't need to match (">)? and (<a\/>) as it will only appear when together.

 

I found conditional patterns (?(condition)yes-pattern|no-patter) but couldn't figure out how to use them and if it's even possible to do.

 

Any help much appreciated.

Link to comment
https://forums.phpfreaks.com/topic/98020-conditional-subpattern/
Share on other sites

It was a thing for friend, he wanted to replace all e-mails, e.g.:

 

[email protected]
mailto:[email protected]
<a href="mailto:[email protected]">[email protected]</a>

 

with his <script> that would document.write the mail - as an anti-spam feature (although this solution is terrible).

 

So I created this function, to accomodate for all three possibilites (I know it has flaws):

 

<?php
#
function removeMails($text){   
#
        $pattern = '_(?:<a href=")?(?:mailto:)?([-[:alnum:]]+?)@([-[:alnum:]]+?)\.([-[:alnum:]]{2,}?)(?:">[^"\']+</a>)?_i';
#
        $replace = "<script type='text/javascript'>spam_email('%s', '@', '%s', '%s');</script>";
#
        $sanitize = create_function('$matches', 'return sprintf("<script type=\'text/javascript\'>spam_email(\'%s\', \'@\', \'%s\', \'%s\');</script>", $matches[3], $matches[2], $matches[1]);');
#
        return preg_replace_callback($pattern, $sanitize, $text);
#
}

 

Only thing I'm curious about is whether I can put a conditional pattern in there as I said above.

 

P.S.: I know the e-mail pattern is lame, I'm going to replace it with better one. Not the RFC compliant, though (lol).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.