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
https://forums.phpfreaks.com/topic/234649-preg_replace-number/
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
https://forums.phpfreaks.com/topic/234649-preg_replace-number/#findComment-1205874
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
https://forums.phpfreaks.com/topic/234649-preg_replace-number/#findComment-1205901
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
https://forums.phpfreaks.com/topic/234649-preg_replace-number/#findComment-1205922
Share on other sites

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.