tags:

views:

373

answers:

1

What I thought was going to be an easy implementation of two lines of code and a function, turned out to be made of fail.

On my webpage, I want to be able to type [text]1[/text], and what it will do is pull the title of that ID.

function textFormat($text) {
    $raw = array(
        '\'\[text\](?P<id>.*?)\[/text\]\'is'
    );

    $out = array (
        '<a href="index.php?function=getData&reference=text&id=$1">' . getTextTitle() . '</a>'
    );

    preg_replace($raw, $out, $text);
    return $text;
}

function getTextTitle($id) {
     $sql = mysql_query("SELECT title FROM text WHERE id = $id");
     return mysql_result($sql);
}

So, here's the lovely little problem: As one can tell, I'm calling a function with a numeric-titled variable, which works great in the quotation marks, but as we know, PHP doesn't like that. So, I opted for a named group. Using $regs['id'] fails to work.

Am I doing something wrong?

Am I going about this the wrong way?

+1  A: 

Well, you're certainly doing it in a radically different way than I ever would, but I think something not too far off from what you're attempting may possibly work. Try this:

function textFormat($text) {
    $raw = array(
        '\'\[text\](?P<id>.*?)\[/text\]\'ise'
    );
    $out = array (
        '\'<a href="index.php?function=getData&reference=text&id=$1">\' . getTextTitle(\'$1\') . \'</a>\''
    );
    preg_replace($raw, $out, $text);
    return $text;
}

function getTextTitle($id) {
     $sql = mysql_query("SELECT title FROM text WHERE id = '" . mysql_real_escape_string($id) . "'");
     $res = mysql_result($sql);
     $row = mysql_fetch_array($res);
     return $row ? $row[0] : 'invalid ID';
}

Your original getTextTitle() would, unless something else is going on I'm not aware of, let anyone do anything they liked to your database via SQL injection, by the way. You're welcome.

Also, I don't know what that (?P<id> noise is about in the regex, so I'm assuming it's needed for some reason and leaving it alone. I do not know whether this is correct.

chaos
The (?P<id> was meant to be a named group, so that'd it return as $regs['id'], this doesn't work apparently; as for the security issue, I appreciate it--I've already put in a system of fixing that (by ensuring that only Administrators can use [text]$num[/text]. Another way would have to been for the capturing group to be (\d+?) instead of (.*?). You made mention that this isn't how you'd approach it--I'm curious, how would you?
Nikolai Echternacht
In addition, thank you; this code is now working, though I had to scrap <code>$res = mysql_result($sql); $row = mysql_fetch_array($res);</code> All this did was generate a profuse amount of errors. I tinkered with it, changing <code>return $row</code> to say $res, but in that instance, it'd just return "invalid ID".
Nikolai Echternacht