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

Link to comment
Share on other sites

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!

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.