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
https://forums.phpfreaks.com/topic/122601-complex-find-and-replace/
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.

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

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.