Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top