lordfrikk Posted March 26, 2008 Share Posted March 26, 2008 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. Quote Link to comment Share on other sites More sharing options...
effigy Posted March 26, 2008 Share Posted March 26, 2008 What pattern are you using to match "LINK"? Why not use it by itself, regardless of the tags presence? Quote Link to comment Share on other sites More sharing options...
lordfrikk Posted March 27, 2008 Author Share Posted March 27, 2008 It was a thing for friend, he wanted to replace all e-mails, e.g.: email@email.com mailto:email@email.com <a href="mailto:email@email.com">email@email.com</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). Quote Link to comment Share on other sites More sharing options...
discomatt Posted March 27, 2008 Share Posted March 27, 2008 http://www.perlmonks.org/?node_id=609009 That might help you Quote Link to comment Share on other sites More sharing options...
lordfrikk Posted April 2, 2008 Author Share Posted April 2, 2008 Thanks, I'll look into it. it requires THINKING :-D Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.