对于非常基本的降价,这些正则表达式是否有效?

时间:2013-01-15 00:53:36

标签: php mysql regex code-injection

关于正则表达式的一个简单问题:这个代码是否适用于我需要做的任何修饰? (即这可以输入数据库并且安全吗?)

function markdown2html($text) {
        $text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
    // Strong Emphasis
    $text = preg_replace('/__(.+?)__/s', '<strong>$1</strong>', $text);
    $text = preg_replace('/\*\*(.+?)\*\*/s', '<strong>$1</strong>', $text);

    // Underline
    $text = preg_replace('/_([^_]+)_/', '<p style="text-decoration: underline;">$1</p>', $text);
    //Italic
    $text = preg_replace('/\*([^\*]+)\*/', '<em>$1</em>', $text);

    // Windows to Unix
    $text = str_replace('\r\n', '\n', $text);
    // Macintosh to Unix
    $text = str_replace('\r', '\n', $text);

    //Paragraphs
    $text = '<p>' . str_replace("\n\n", '</p><p>', $text) . '</p>';
    $text = str_replace("\n", '<br />', $text);

    // [Linked Text](Url)   
   $text = preg_replace('/\[([^\]]+)]\(([a-z0-9._~:\/?#@!$&\'()*+,;=%]+)\)/i', '<a href="$2">$1</a>', $text);

   return $text;

}

3 个答案:

答案 0 :(得分:1)

不,绝对没有。

您的代码与SQL无关 - 它根本不会修改'\个字符。将此函数的格式化功能与SQL转义相结合是愚蠢的。

您的代码也可能在某些情况下引入HTML注入 - 我特别怀疑链接正则表达式的URL。如果没有合适的解析器,我就不会相信它了。

答案 1 :(得分:0)

不,通过该功能后数据无法保证安全。

您需要转义sql敏感字符或使用PDO / Mysqli。无论如何,Preapared语句都更方便。

不要使用旧的黑客攻击方式,即:

$query = 'select * from table where col = '.$value;

你只是在那里遇到麻烦。

答案 2 :(得分:0)

我突然想到了一些事情:

我相信前两个正则表达式('/__(.+?)__/s'和相应的*)处理___word___和***字***错误 - 他们会将第三个字符视为单词,所以你会得到 * word *(其中第一个*是粗体而后面的是粗体)而不是 word

在第三个('/_([^_]+)_/')上,它是否适合

  

做_not_做那个

变成

  

do&lt; p style =“text-decoration:underline;”&gt; not&lt; / p&gt;那样做

当然我 说如果您解决这些问题就可以使用。