peter_anderson Posted April 25, 2011 Share Posted April 25, 2011 I need to find <<!--{rep_[A NUMBER]}-->> and replace it with a function. I am currently using: <?php $rep['find'] = '<<!--{rep_(.*?)}-->>'; $rep['replace'] = ''.$reputation->postRating('$1').''; $html = preg_replace($rep['find'],$rep['replace'],$html); ?> But when I check the value in reputation->postRating, it doesn't match. Eg, <<!--{rep_4}-->> in the function is passed as 0 (after being passed through intval()). Can anybody help? It's probably something silly but I can't work it out. Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted April 25, 2011 Share Posted April 25, 2011 use [0-9] character set or just \d when looking for numbers. You also need to set your pattern delimiters too. <?php $rep['find'] = '/<<!--{rep_([0-9]+)}-->>/e'; $rep['replace'] = "\$reputation->postRating('$1')"; $html = preg_replace($rep['find'], $rep['replace'], $html); ?> You'll notice I used the e pattern modifier, Otherwise the number will not be passed to your postRating function. Quote Link to comment Share on other sites More sharing options...
peter_anderson Posted April 25, 2011 Author Share Posted April 25, 2011 use [0-9] character set or just \d when looking for numbers. You also need to set your pattern delimiters too. <?php $rep['find'] = '/<<!--{rep_([0-9]+)}-->>/e'; $rep['replace'] = "\$reputation->postRating('$1')"; $html = preg_replace($rep['find'], $rep['replace'], $html); ?> You'll notice I used the e pattern modifier, Otherwise the number will not be passed to your postRating function. Thank you, that's fixed it. I know there was something small Quote Link to comment Share on other sites More sharing options...
.josh Posted April 25, 2011 Share Posted April 25, 2011 As a note, the e modifier basically does the equivalent of running eval on the replacement argument of preg_replace(). So if you use it, you have to have valid php syntax in that argument (treat it as php syntax). In general, if you find yourself in the position of needing to use the e modifier for preg_replace(), you should instead consider using preg_replace_callback. 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.