Jump to content

string replace with function?


bcamp1973

Recommended Posts

i want to parse the page content looking for one or more instances of the string %MATCH-XX% where XX is an integer. I then want to replace that string with the code generated from a function that uses the XX integer as it's only argument. So, for example...

 

i start with

$content = '<p>This paragraph has a %MATCH-23% in it</p>';

 

and then my function

function parse_match($XX,$content){
   // work some magic with $content & $XX
   return '<span>with a number'.$XX.'</span>';
}

 

produces this

<p>This paragraph has a <span>with a number 23</span> in it</p>

 

I need to be able to do this in PHP 4.1 as well...i'm at a loss at this point :(

Link to comment
https://forums.phpfreaks.com/topic/92485-string-replace-with-function/
Share on other sites

Are we sure this will work with the version of you are using?

 

I'm have mad problems with regex on older PHP versions. There is a great changelog for the functionality on the PHP.net site, but it's hard to find, and I didn't bookmark it.

 

So search around on the php.net site for the changelog if that regex code doesn't work on your version of php, they usually have suggestions

Try this out:

 

<?php
function parse_match($matches) {
     return '<span>with a number ' . $matches[0] . '</span>';
}
$content = 'This is a string %MATCH-23% in it';
$content = preg_replace_callback('/\%MATCH-(\d+)\%/i', 'parse_match', $content);
print $content;
?>

Try this out:

 

<?php
function parse_match($matches) {
     return '<span>with a number ' . $matches[0] . '</span>';
}
$content = 'This is a string %MATCH-23% in it';
$content = preg_replace_callback('/\%MATCH-(\d+)\%/i', 'parse_match', $content);
print $content;
?>

 

that did it!  thanks Bauer418!

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.