Jump to content

preg_replace number


peter_anderson

Recommended Posts

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.