Jump to content

Some Kind Of Replace


shaneg55

Recommended Posts

I have this html tag <navigation></navigation>. I want to find any and all references to <navigation></navigation>, retrieve the int value thats between the <navigation>3</navigation> (in this case the number 3), run an sql query and return a record where the id is the value between <navigation>3</navigation> (again in this case 3) and replace the entire tag  with whatever was returned from the sql query.

 

note: there could be more than one navigation tag within my string. plus a bunch of other html. i want to keep all the other and find, build, and replace new text where the navigation tag is.

Link to comment
https://forums.phpfreaks.com/topic/213049-some-kind-of-replace/
Share on other sites

Just for fun, here's an example:

 

$content = preg_replace('#(<navigation>([\d]+)</navigation>)#e', 'get_navigation(\\2, "\\1")', $content);

function get_navigation($id, $original) {
    if($row = mysql_fetch_assoc(mysql_query("SELECT something FROM table WHERE id = $id"))) {
        return $row['something'];
    } else {
        return $original;
    }
}

Just for fun, here's an example:

 

$content = preg_replace('#(<navigation>([\d]+)</navigation>)#e', 'get_navigation(\\2, "\\1")', $content);

function get_navigation($id, $original) {
    if($row = mysql_fetch_assoc(mysql_query("SELECT something FROM table WHERE id = $id"))) {
        return $row['something'];
    } else {
        return $original;
    }
}

 

Shouldn't that be preg_replace_callback()?

Just for fun, here's an example:

 

$content = preg_replace('#(<navigation>([\d]+)</navigation>)#e', 'get_navigation(\\2, "\\1")', $content);

function get_navigation($id, $original) {
    if($row = mysql_fetch_assoc(mysql_query("SELECT something FROM table WHERE id = $id"))) {
        return $row['something'];
    } else {
        return $original;
    }
}

 

Shouldn't that be preg_replace_callback()?

AbraCadaver is using the 'e' pattern modifier. This will eval the code in the replacement. Which will call the function get_navigation()

And if I had looked, I would have seen that.  I went to the manual before commenting, just to be sure.  Missed the note on the e modifier though.  Never used it, but that is one worth noting.  Always just used preg_replace_callback().

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.