Jump to content

Complex find and replace


drisate

Recommended Posts

Hey guys. I have a client that would like me to create a code that would replace a tag by a module in his emails

 

Ex: [JOB=10]

 

Would output the last 10 posted jobs. If the tag was a simple [JOB] I would just search it and replace it ... but the problem is not only i have to find it, but I have to extract the unknown value, use it to create a replace output, then replace the unknown string by the replace output ...

 

Help! Lol

Link to comment
Share on other sites

I'm not going to write the whole code for you now, but you could use regex to find the tags. With the results of that tag, split in to tag (ex. "JOB", "other tags" ), and value. What you would then do is create a switch statement for the tag value. Then you make a function for example getJobs( $amount ), whereas $amount would be the value extracted with regex. Then you would do like this:

 

$replace = getJobs( $amount );

 

And replace the tag by $replace. Hope you can work with this information.

Link to comment
Share on other sites

<?php
function getJobs($limit=NULL) {
  $query = "SELECT * FROM jobs";
  if ($limit != null) {
        $query .= " LIMIT $limit";
  }
 $res = mysql_query($query) or die(mysql_error());
 while ($row = mysql_fetch_assoc($res)) {
         $jobs[] = $row['name'];
 }
 return implode('<br />', $jobs);
}
 
$str = "Here's some of our latest jobs:
[JOB=10]";
$newstr = preg_replace('/\[JOB(=([0-9]+))?\]/ie', "getJobs($2)", $str);

 

Obviously use the correct query and column names.

 

EDIT: Lol, I had the function named getJobs() before QuietWhistler posted (I was writing this code).  Funny. :D  Anyway, it should work like this, anything else would probably over-complicate it.

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.